一 常用容器举例
1 vector:
vector类似于动态数组,直接访问元素,从后面快速插入或者删除,示例代码如下:
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <vector>//包含vector
- using namespace std;//指定命名空间
- int main()
- {
- cout<<"----------vector test-----------"<<endl;
- //定义一个vector
- vector <int> vect;
- vector <int> vect1(12);//12个int类型元素,每个元素的初始值均为0
- vector <int> vect2(12,9);//12个int,初试值均为9
- //使用数组初始化vector
- int a[]={0,1,2,3,4,5,6,7,8,9,0};
- //vector <数据类型> <容器名> (<开始地址>,<结束地址的下一个地址> )。执行过vt中元素为1,2,3
- vector <int> vt(a+1,a+4);
- //在尾部压入3个值
- vt.push_back(1);
- vt.push_back(2);
- vt.push_back(3);
- //定义迭代器iterator
- vector <int>::iterator iter=vt.begin();//起始地址
- vector <int>::iterator iter_end=vt.end();//结束地址,两个地址都是指针类型
- //遍历vt
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- //弹出一个元素
- vt.pop_back();
- //以下两行重新获得起始和结尾地址
- iter=vt.begin();
- iter_end=vt.end();
- cout<<"----------executed pop_back------"<<endl;
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- //插入元素
- cout<<"----------insert into------------"<<endl;
- //插入格式:vector.insert(<起始地址>,<插入的数量>,<元素值>);如果插入的数量为1,则第二个参数可以被省略
- vt.insert(vt.begin()+1,3,9);
- iter=vt.begin();
- iter_end=vt.end();
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- //删除元素
- cout<<"----------erase-------------------"<<endl;
- //删除格式1为:vector.erase(<删除元素的地址>);
- //删除格式2为:vector.erase(<删除元素的起始地址>,<终止地址>);
- iter=vt.begin();
- iter_end=vt.end();
- vt.erase(iter+1,iter_end);//删除第二个到最后一个的元素
- iter_end=vt.end();
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- return 1;
- }
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <vector>//包含vector
- using namespace std;//指定命名空间
- int main()
- {
- cout<<"----------vector test-----------"<<endl;
- //定义一个vector
- vector <int> vect;
- vector <int> vect1(12);//12个int类型元素,每个元素的初始值均为0
- vector <int> vect2(12,9);//12个int,初试值均为9
- //使用数组初始化vector
- int a[]={0,1,2,3,4,5,6,7,8,9,0};
- //vector <数据类型> <容器名> (<开始地址>,<结束地址的下一个地址> )。执行过vt中元素为1,2,3
- vector <int> vt(a+1,a+4);
- //在尾部压入3个值
- vt.push_back(1);
- vt.push_back(2);
- vt.push_back(3);
- //定义迭代器iterator
- vector <int>::iterator iter=vt.begin();//起始地址
- vector <int>::iterator iter_end=vt.end();//结束地址,两个地址都是指针类型
- //遍历vt
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- //弹出一个元素
- vt.pop_back();
- //以下两行重新获得起始和结尾地址
- iter=vt.begin();
- iter_end=vt.end();
- cout<<"----------executed pop_back------"<<endl;
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- //插入元素
- cout<<"----------insert into------------"<<endl;
- //插入格式:vector.insert(<起始地址>,<插入的数量>,<元素值>);如果插入的数量为1,则第二个参数可以被省略
- vt.insert(vt.begin()+1,3,9);
- iter=vt.begin();
- iter_end=vt.end();
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- //删除元素
- cout<<"----------erase-------------------"<<endl;
- //删除格式1为:vector.erase(<删除元素的地址>);
- //删除格式2为:vector.erase(<删除元素的起始地址>,<终止地址>);
- iter=vt.begin();
- iter_end=vt.end();
- vt.erase(iter+1,iter_end);//删除第二个到最后一个的元素
- iter_end=vt.end();
- for(;iter!=iter_end;iter++)
- {
- cout<<*iter<<endl;
- }
- return 1;
- }
2 list
list 为双向链表,可以从任何地方插入或者删除的,其示例代码如下:
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <list>
- using namespace std;
- void main()
- {
- list<int> c1;
- c1.push_back(1);//从尾部push数据(结点)到list中
- c1.push_back(2);
- c1.push_back(3);
- c1.push_back(4);
- c1.push_front(0);//从头部push数据(结点)到list中
- c1.pop_back();//从尾部pop数据(结点)出去
- int& i = c1.back();//获取list中尾部数据(结点)
- const int& ii = c1.front();//获取list中头部 数据(结点)
- cout << "The last integer of c1 is " << i << endl;
- cout << "The front interger of c1 is " << ii << endl;
- cout << "for循环读出数据举例:" << endl;
- //循环遍历数据举例
- list<int>::iterator it; //定义遍历指示器(类似于int i=0)
- for(it = c1.begin() ; it != c1.end() ;it++)
- {
- cout << *it << endl;
- }
- system("pause");
- }
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <list>
- using namespace std;
- void main()
- {
- list<int> c1;
- c1.push_back(1);//从尾部push数据(结点)到list中
- c1.push_back(2);
- c1.push_back(3);
- c1.push_back(4);
- c1.push_front(0);//从头部push数据(结点)到list中
- c1.pop_back();//从尾部pop数据(结点)出去
- int& i = c1.back();//获取list中尾部数据(结点)
- const int& ii = c1.front();//获取list中头部 数据(结点)
- cout << "The last integer of c1 is " << i << endl;
- cout << "The front interger of c1 is " << ii << endl;
- cout << "for循环读出数据举例:" << endl;
- //循环遍历数据举例
- list<int>::iterator it; //定义遍历指示器(类似于int i=0)
- for(it = c1.begin() ; it != c1.end() ;it++)
- {
- cout << *it << endl;
- }
- system("pause");
- }
3 deque:
deque: 是一个double-ended queue,
1)支持随即存取,也就是[]操作符,
2)支持两端操作,push(pop)-back(front),在两端操作上与list效率差不多
因此在实际使用时,如何选择这三个容器中哪一个,应根据你的需要而定,一般应遵循下面的原则:
1、如果你需要高效的随即存取,而不在乎插入和删除的效率,使用vector
2、如果你需要大量的插入和删除,而不关心随即存取,则应使用list
3、如果你需要随即存取,而且关心两端数据的插入和删除,则应使用deque。
示例代码如下:
[cpp] view
plaincopyprint?
- /*deque: 是一个double-ended queue,
- 1)支持随即存取,也就是[]操作符,
- 2)支持两端操作,push(pop)-back(front),在两端操作上与list效率差不多
- 因此在实际使用时,如何选择这三个容器中哪一个,应根据你的需要而定,一般应遵循下面的原则:
- 1、如果你需要高效的随即存取,而不在乎插入和删除的效率,使用vector
- 2、如果你需要大量的插入和删除,而不关心随即存取,则应使用list
- 3、如果你需要随即存取,而且关心两端数据的插入和删除,则应使用deque。
- */
- #include <iostream>
- #include <deque>
- using namespace std;
- void printDeque(const deque<int>& d)
- {
- cout<<"\n使用下标:\n";
- for (unsigned int i = 0; i < d.size(); i++)
- {
- cout<<"d["<<i<<"] = "<<d[i]<<", ";
- }
- cout<<"\n使用迭代器\n";
- deque<int>::const_iterator iter = d.begin();
- for (;iter != d.end(); iter ++)
- {
- cout<<"d["<<iter-d.begin()<<"] = "<<(*iter)<<", ";
- }
- cout<<endl;
- }
- void main()
- {
- //创建deque
- deque<int> d1; //创建一个没有任何元素的deque对象
- deque<int> d2(10); //创建一个具有10个元素的deque对象,每个元素值为默认
- deque<double> d3(10, 5.5); //创建一个具有10个元素的deque对象,每个元素的初始值为5.5
- deque<double> d4(d3); //通过拷贝一个deque对象的元素值, 创建一个新的deque对象
- //初始化赋值:同vector一样,使用尾部插入函数push_back()
- for (int i = 1; i < 6 ; i++)
- d1.push_back(i*10);
- //遍历元素: 1-下标方式 2-迭代器方式 反向遍历(略)
- cout<<"printDeque(d1) : "<<endl;
- printDeque(d1);
- //元素插入:尾部插入用push_back(),头部插入用push_front(),其它位置插入用insert(&pos, elem)
- cout<<"d1.push_front(100): "<<endl;
- d1.push_front(100);
- printDeque(d1);
- cout<<"d1.insert(d1.begin()+3, 200): "<<endl; //支持随机存取(即[]操作符),所以begin()可以+3
- d1.insert(d1.begin()+2,200);
- printDeque(d1);
- //元素删除 尾部删除用pop_back();头部删除用pop_front();
- //任意迭代位置或迭代区间上的元素删除用erase(&pos)/erase(&first, &last);删除所有元素用clear();
- cout<<"d1.pop_front(): "<<endl;
- d1.pop_front();
- printDeque(d1);
- cout<<"d1.erase(d1.begin()+1): "<<endl;
- d1.erase(d1.begin()+1); //删除第2个元素d1[1]
- printDeque(d1);
- cout<<"d1.erase(d1.begin(), d1.begin() + 2) = "<<endl;
- d1.erase(d1.begin(), d1.begin() + 2);
- printDeque(d1);
- cout<<"d1.clear() :"<<endl;
- d1.clear();
- printDeque(d1);
- }
[cpp] view
plaincopyprint?
- /*deque: 是一个double-ended queue,
- 1)支持随即存取,也就是[]操作符,
- 2)支持两端操作,push(pop)-back(front),在两端操作上与list效率差不多
- 因此在实际使用时,如何选择这三个容器中哪一个,应根据你的需要而定,一般应遵循下面的原则:
- 1、如果你需要高效的随即存取,而不在乎插入和删除的效率,使用vector
- 2、如果你需要大量的插入和删除,而不关心随即存取,则应使用list
- 3、如果你需要随即存取,而且关心两端数据的插入和删除,则应使用deque。
- */
- #include <iostream>
- #include <deque>
- using namespace std;
- void printDeque(const deque<int>& d)
- {
- cout<<"\n使用下标:\n";
- for (unsigned int i = 0; i < d.size(); i++)
- {
- cout<<"d["<<i<<"] = "<<d[i]<<", ";
- }
- cout<<"\n使用迭代器\n";
- deque<int>::const_iterator iter = d.begin();
- for (;iter != d.end(); iter ++)
- {
- cout<<"d["<<iter-d.begin()<<"] = "<<(*iter)<<", ";
- }
- cout<<endl;
- }
- void main()
- {
- //创建deque
- deque<int> d1; //创建一个没有任何元素的deque对象
- deque<int> d2(10); //创建一个具有10个元素的deque对象,每个元素值为默认
- deque<double> d3(10, 5.5); //创建一个具有10个元素的deque对象,每个元素的初始值为5.5
- deque<double> d4(d3); //通过拷贝一个deque对象的元素值, 创建一个新的deque对象
- //初始化赋值:同vector一样,使用尾部插入函数push_back()
- for (int i = 1; i < 6 ; i++)
- d1.push_back(i*10);
- //遍历元素: 1-下标方式 2-迭代器方式 反向遍历(略)
- cout<<"printDeque(d1) : "<<endl;
- printDeque(d1);
- //元素插入:尾部插入用push_back(),头部插入用push_front(),其它位置插入用insert(&pos, elem)
- cout<<"d1.push_front(100): "<<endl;
- d1.push_front(100);
- printDeque(d1);
- cout<<"d1.insert(d1.begin()+3, 200): "<<endl; //支持随机存取(即[]操作符),所以begin()可以+3
- d1.insert(d1.begin()+2,200);
- printDeque(d1);
- //元素删除 尾部删除用pop_back();头部删除用pop_front();
- //任意迭代位置或迭代区间上的元素删除用erase(&pos)/erase(&first, &last);删除所有元素用clear();
- cout<<"d1.pop_front(): "<<endl;
- d1.pop_front();
- printDeque(d1);
- cout<<"d1.erase(d1.begin()+1): "<<endl;
- d1.erase(d1.begin()+1); //删除第2个元素d1[1]
- printDeque(d1);
- cout<<"d1.erase(d1.begin(), d1.begin() + 2) = "<<endl;
- d1.erase(d1.begin(), d1.begin() + 2);
- printDeque(d1);
- cout<<"d1.clear() :"<<endl;
- d1.clear();
- printDeque(d1);
- }
4 容器适配器:stack
(1)可用 vector, list, deque来实现
(2)缺省情况下,用deque实现
template<classT, class Cont = deque<T> >
class stack { ….. };
(3)用 vector和deque实现,比用list实现性能好
(4)stack是后进先出的数据结构,
(5)只能插入、删除、访问栈顶的元素的操作: push: 插入元素pop: 弹出元素 top: 返回栈顶元素的引用
测试代码如下:
[cpp] view
plaincopyprint?
- <SPAN style="FONT-SIZE: 16px">#include <iostream>
- #include <Stack>
- using namespace std;
- void main()
- {
- stack<double> s;//可以是各种数据类型;
- for( int i=0; i < 10; i++ )
- s.push(i);
- while(!s.empty())
- {
- printf("%lf\n",s.top());
- s.pop();
- }
- cout << "the size of s: " << s.size() << endl;
- }
- </SPAN>
[cpp] view
plaincopyprint?
- <span style="font-size:16px">#include <iostream>
- #include <Stack>
- using namespace std;
- void main()
- {
- stack<double> s;//可以是各种数据类型;
- for( int i=0; i < 10; i++ )
- s.push(i);
- while(!s.empty())
- {
- printf("%lf\n",s.top());
- s.pop();
- }
- cout << "the size of s: " << s.size() << endl;
- }
- </span>
5 deque
可以用 list和deque实现,缺省情况下用deque实现
template<class T, class Cont = deque<T>>
class queue { … };
FIFO先进先出的数据结构,也有push,pop,top函数,但是push发生在队尾,pop,top发生在队头,
示例代码如下:
[cpp] view
plaincopyprint?
- /************************************************************************/
- /*
- 详细用法:
- 定义一个queue的变量 queue<Type> M
- 查看是否为空范例 M.empty() 是的话返回1,不是返回0;
- 从已有元素后面增加元素 M.push()
- 输出现有元素的个数 M.size()
- 显示第一个元素 M.front()
- 显示最后一个元素 M.back()
- 清除第一个元素 M.pop()
- */
- /************************************************************************/
- #include <iostream>
- #include <queue>
- #include <assert.h>
- using namespace std;
- int main()
- {
- queue <int> myQ;
- int i;
- cout<< "现在 queue 是否 empty? "<< myQ.empty() << endl;
- for( i =0; i<10 ; i++)
- {
- myQ.push(i);
- }
- for( i=0; i<myQ.size(); i++)
- {
- printf("myQ.size():%d\n",myQ.size());
- cout << myQ.front()<<endl;
- myQ.pop();
- }
- system("PAUSE");
- return 0;
- }
[cpp] view
plaincopyprint?
- /************************************************************************/
- /*
- 详细用法:
- 定义一个queue的变量 queue<Type> M
- 查看是否为空范例 M.empty() 是的话返回1,不是返回0;
- 从已有元素后面增加元素 M.push()
- 输出现有元素的个数 M.size()
- 显示第一个元素 M.front()
- 显示最后一个元素 M.back()
- 清除第一个元素 M.pop()
- */
- /************************************************************************/
- #include <iostream>
- #include <queue>
- #include <assert.h>
- using namespace std;
- int main()
- {
- queue <int> myQ;
- int i;
- cout<< "现在 queue 是否 empty? "<< myQ.empty() << endl;
- for( i =0; i<10 ; i++)
- {
- myQ.push(i);
- }
- for( i=0; i<myQ.size(); i++)
- {
- printf("myQ.size():%d\n",myQ.size());
- cout << myQ.front()<<endl;
- myQ.pop();
- }
- system("PAUSE");
- return 0;
- }
二 常用算法
1 count()and count_if()
count()在序列中统计某个值出现的次数
count_if()在序列中统计与某谓词匹配的次数
示例代码如下:
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <algorithm>
- #include <functional>
- #include <string>
- #include <vector>
- using namespace std;
- void CountFuc()
- {
- const int VECTOR_SIZE = 8 ;
- // Define a template class vector of strings
- typedef vector<string > StringVector ;
- //Define an iterator for template class vector of strings
- typedef StringVector::iterator StringVectorIt ;
- StringVector NamesVect(VECTOR_SIZE) ; //vector containing names
- string value("Sea") ; // stores the value used
- // to count matching elements
- StringVectorIt start, end, it ;
- int result = 0 ; // stores count of elements
- // that match value.
- // Initialize vector NamesVect
- NamesVect[0] = "She" ;
- NamesVect[1] = "Sells" ;
- NamesVect[2] = "Sea" ;
- NamesVect[3] = "Shells" ;
- NamesVect[4] = "by" ;
- NamesVect[5] = "the" ;
- NamesVect[6] = "Sea" ;
- NamesVect[7] = "Shore" ;
- start = NamesVect.begin() ; // location of first
- // element of NamesVect
- end = NamesVect.end() ; // one past the location
- // last element of NamesVect
- // print content of NamesVect
- cout << "NamesVect { " ;
- for(it = start; it != end; it++)
- cout << *it << " " ;
- cout << " }\n" << endl ;
- // Count the number of elements in the range [first, last +1)
- // that match value.
- result = count(start, end, value) ;
- // print the count of elements that match value
- cout << "Number of elements that match \"Sea\" = "
- << result << endl ;
- }
- int MatchFirstChar( const string& str)
- {
- string s("S") ;
- return s == str.substr(0,1) ;
- }
- void CountIfFuc()
- {
- const int VECTOR_SIZE = 8 ;
- // Define a template class vector of strings
- typedef vector<string > StringVector ;
- //Define an iterator for template class vector of strings
- typedef StringVector::iterator StringVectorIt ;
- StringVector NamesVect(VECTOR_SIZE) ; //vector containing names
- StringVectorIt start, end, it ;
- int result = 0 ; // stores count of elements
- // that match value.
- // Initialize vector NamesVect
- NamesVect[0] = "She" ;
- NamesVect[1] = "Sells" ;
- NamesVect[2] = "Sea" ;
- NamesVect[3] = "Shells" ;
- NamesVect[4] = "by" ;
- NamesVect[5] = "the" ;
- NamesVect[6] = "Sea" ;
- NamesVect[7] = "Shore" ;
- start = NamesVect.begin() ; // location of first
- // element of NamesVect
- end = NamesVect.end() ; // one past the location
- // last element of NamesVect
- // print content of NamesVect
- cout << "NamesVect { " ;
- for(it = start; it != end; it++)
- cout << *it << " " ;
- cout << " }\n" << endl ;
- // Count the number of elements in the range [first, last +1)
- // that start with letter ‘S‘
- result = count_if(start, end, MatchFirstChar) ;
- // print the count of elements that start with letter ‘S‘
- cout << "Number of elements that start with letter \"S\" = "
- << result << endl ;
- }
- void main()
- {
- CountFuc();
- CountIfFuc();
- }
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <algorithm>
- #include <functional>
- #include <string>
- #include <vector>
- using namespace std;
- void CountFuc()
- {
- const int VECTOR_SIZE = 8 ;
- // Define a template class vector of strings
- typedef vector<string > StringVector ;
- //Define an iterator for template class vector of strings
- typedef StringVector::iterator StringVectorIt ;
- StringVector NamesVect(VECTOR_SIZE) ; //vector containing names
- string value("Sea") ; // stores the value used
- // to count matching elements
- StringVectorIt start, end, it ;
- int result = 0 ; // stores count of elements
- // that match value.
- // Initialize vector NamesVect
- NamesVect[0] = "She" ;
- NamesVect[1] = "Sells" ;
- NamesVect[2] = "Sea" ;
- NamesVect[3] = "Shells" ;
- NamesVect[4] = "by" ;
- NamesVect[5] = "the" ;
- NamesVect[6] = "Sea" ;
- NamesVect[7] = "Shore" ;
- start = NamesVect.begin() ; // location of first
- // element of NamesVect
- end = NamesVect.end() ; // one past the location
- // last element of NamesVect
- // print content of NamesVect
- cout << "NamesVect { " ;
- for(it = start; it != end; it++)
- cout << *it << " " ;
- cout << " }\n" << endl ;
- // Count the number of elements in the range [first, last +1)
- // that match value.
- result = count(start, end, value) ;
- // print the count of elements that match value
- cout << "Number of elements that match \"Sea\" = "
- << result << endl ;
- }
- int MatchFirstChar( const string& str)
- {
- string s("S") ;
- return s == str.substr(0,1) ;
- }
- void CountIfFuc()
- {
- const int VECTOR_SIZE = 8 ;
- // Define a template class vector of strings
- typedef vector<string > StringVector ;
- //Define an iterator for template class vector of strings
- typedef StringVector::iterator StringVectorIt ;
- StringVector NamesVect(VECTOR_SIZE) ; //vector containing names
- StringVectorIt start, end, it ;
- int result = 0 ; // stores count of elements
- // that match value.
- // Initialize vector NamesVect
- NamesVect[0] = "She" ;
- NamesVect[1] = "Sells" ;
- NamesVect[2] = "Sea" ;
- NamesVect[3] = "Shells" ;
- NamesVect[4] = "by" ;
- NamesVect[5] = "the" ;
- NamesVect[6] = "Sea" ;
- NamesVect[7] = "Shore" ;
- start = NamesVect.begin() ; // location of first
- // element of NamesVect
- end = NamesVect.end() ; // one past the location
- // last element of NamesVect
- // print content of NamesVect
- cout << "NamesVect { " ;
- for(it = start; it != end; it++)
- cout << *it << " " ;
- cout << " }\n" << endl ;
- // Count the number of elements in the range [first, last +1)
- // that start with letter ‘S‘
- result = count_if(start, end, MatchFirstChar) ;
- // print the count of elements that start with letter ‘S‘
- cout << "Number of elements that start with letter \"S\" = "
- << result << endl ;
- }
- void main()
- {
- CountFuc();
- CountIfFuc();
- }
2 find and find_if
find 在序列中找出某个值的第一次出现的位置
find_if 在序列中找出符合某谓词的第一个元素
示例代码如下:
[cpp] view
plaincopyprint?
- #include <algorithm>
- #include <iostream>
- using namespace std;
- void FindFuc()
- {
- const int ARRAY_SIZE = 8 ;
- int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
- int *location ; // stores the position of the first
- // matching element.
- int i ;
- int value = 4 ;
- // print content of IntArray
- cout << "IntArray { " ;
- for(i = 0; i < ARRAY_SIZE; i++)
- cout << IntArray[i] << ", " ;
- cout << " }" << endl ;
- // Find the first element in the range [first, last + 1)
- // that matches value.
- location = find(IntArray, IntArray + ARRAY_SIZE, value) ;
- //print the matching element if any was found
- if (location != IntArray + ARRAY_SIZE) // matching element found
- cout << "First element that matches " << value
- << " is at location " << location - IntArray << endl;
- else // no matching element was
- // found
- cout << "The sequence does not contain any elements"
- << " with value " << value << endl ;
- }
- int IsOdd( int n)
- {
- return n % 2 ;
- }
- void FindIfFuc()
- {
- const int ARRAY_SIZE = 8 ;
- int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
- int *location ; // stores the position of the first
- // element that is an odd number
- int i ;
- // print content of IntArray
- cout << "IntArray { " ;
- for(i = 0; i < ARRAY_SIZE; i++)
- cout << IntArray[i] << ", " ;
- cout << " }" << endl ;
- // Find the first element in the range [first, last -1 ]
- // that is an odd number
- location = find_if(IntArray, IntArray + ARRAY_SIZE, IsOdd) ;
- //print the location of the first element
- // that is an odd number
- if (location != IntArray + ARRAY_SIZE) // first odd element found
- cout << "First odd element " << *location
- << " is at location " << location - IntArray << endl;
- else // no odd numbers in the range
- cout << "The sequence does not contain any odd numbers"
- << endl ;
- }
- void main()
- {
- FindFuc();
- FindIfFuc();
- }
[cpp] view
plaincopyprint?
- #include <algorithm>
- #include <iostream>
- using namespace std;
- void FindFuc()
- {
- const int ARRAY_SIZE = 8 ;
- int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
- int *location ; // stores the position of the first
- // matching element.
- int i ;
- int value = 4 ;
- // print content of IntArray
- cout << "IntArray { " ;
- for(i = 0; i < ARRAY_SIZE; i++)
- cout << IntArray[i] << ", " ;
- cout << " }" << endl ;
- // Find the first element in the range [first, last + 1)
- // that matches value.
- location = find(IntArray, IntArray + ARRAY_SIZE, value) ;
- //print the matching element if any was found
- if (location != IntArray + ARRAY_SIZE) // matching element found
- cout << "First element that matches " << value
- << " is at location " << location - IntArray << endl;
- else // no matching element was
- // found
- cout << "The sequence does not contain any elements"
- << " with value " << value << endl ;
- }
- int IsOdd( int n)
- {
- return n % 2 ;
- }
- void FindIfFuc()
- {
- const int ARRAY_SIZE = 8 ;
- int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
- int *location ; // stores the position of the first
- // element that is an odd number
- int i ;
- // print content of IntArray
- cout << "IntArray { " ;
- for(i = 0; i < ARRAY_SIZE; i++)
- cout << IntArray[i] << ", " ;
- cout << " }" << endl ;
- // Find the first element in the range [first, last -1 ]
- // that is an odd number
- location = find_if(IntArray, IntArray + ARRAY_SIZE, IsOdd) ;
- //print the location of the first element
- // that is an odd number
- if (location != IntArray + ARRAY_SIZE) // first odd element found
- cout << "First odd element " << *location
- << " is at location " << location - IntArray << endl;
- else // no odd numbers in the range
- cout << "The sequence does not contain any odd numbers"
- << endl ;
- }
- void main()
- {
- FindFuc();
- FindIfFuc();
- }
3 for_each()
函数声明如下:
template<class InIt, class Fun> Fun for_each(InIt first, InIt last, Fun f);
在区间【first,last)上的每个元素执行f操作
示例代码如下:
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- // prints the cube of integer n
- void PrintCube(int n)
- {
- cout << n * n * n << " " ;
- }
- void main()
- {
- const int VECTOR_SIZE = 8 ;
- // Define a template class vector of integers
- typedef vector<int > IntVector ;
- //Define an iterator for template class vector of integer
- typedef IntVector::iterator IntVectorIt ;
- IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
- IntVectorIt start, end, it ;
- int i ;
- // Initialize vector Numbers
- for (i = 0; i < VECTOR_SIZE; i++)
- Numbers[i] = i + 1 ;
- start = Numbers.begin() ; // location of first
- // element of Numbers
- end = Numbers.end() ; // one past the location
- // last element of Numbers
- // print content of Numbers
- cout << "Numbers { " ;
- for(it = start; it != end; it++)
- cout << *it << " " ;
- cout << " }\n" << endl ;
- // for each element in the range [first, last)
- // print the cube of the element
- for_each(start, end, PrintCube) ;
- cout << "\n\n" ;
- }
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- // prints the cube of integer n
- void PrintCube(int n)
- {
- cout << n * n * n << " " ;
- }
- void main()
- {
- const int VECTOR_SIZE = 8 ;
- // Define a template class vector of integers
- typedef vector<int > IntVector ;
- //Define an iterator for template class vector of integer
- typedef IntVector::iterator IntVectorIt ;
- IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers
- IntVectorIt start, end, it ;
- int i ;
- // Initialize vector Numbers
- for (i = 0; i < VECTOR_SIZE; i++)
- Numbers[i] = i + 1 ;
- start = Numbers.begin() ; // location of first
- // element of Numbers
- end = Numbers.end() ; // one past the location
- // last element of Numbers
- // print content of Numbers
- cout << "Numbers { " ;
- for(it = start; it != end; it++)
- cout << *it << " " ;
- cout << " }\n" << endl ;
- // for each element in the range [first, last)
- // print the cube of the element
- for_each(start, end, PrintCube) ;
- cout << "\n\n" ;
- }
4 unique
unique --常用来删除重复的元素,将相邻的重复的元素移到最后,返回一个iterator指向最后的重复元素,所以用它来删除重复元素时必须先排序
示例代码如下:
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <string>
- using namespace std;
- void main()
- {
- string str;
- vector<string> words;
- while(cin>>str&&str!="#")
- {
- words.push_back(str);
- }
- sort(words.begin(),words.end());
- vector<string>::iterator end_unique =
- unique(words.begin(),words.end());
- words.erase(end_unique,words.end());
- vector<string> ::iterator ite=words.begin();
- for(;ite!=words.end();ite++)
- {
- cout<<*ite<<" ";
- }
- cout<<endl;
- }
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <string>
- using namespace std;
- void main()
- {
- string str;
- vector<string> words;
- while(cin>>str&&str!="#")
- {
- words.push_back(str);
- }
- sort(words.begin(),words.end());
- vector<string>::iterator end_unique =
- unique(words.begin(),words.end());
- words.erase(end_unique,words.end());
- vector<string> ::iterator ite=words.begin();
- for(;ite!=words.end();ite++)
- {
- cout<<*ite<<" ";
- }
- cout<<endl;
- }
5 常用排序算法
常用排列算法如下:
1 sort 对给定区间所有元素进行排序
2 stable_sort 对给定区间所有元素进行稳定排序
3 partial_sort 对给定区间所有元素部分排序
4 partial_sort_copy 对给定区间复制并排序
示例代码如下:
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <algorithm>
- #include <stdlib.h>
- #include <time.h>
- #include <VECTOR>
- using namespace std;
- const int N=10;
- void print(const vector<int>& v)
- {
- vector<int>::const_iterator ite=v.begin();
- for(;ite!=v.end();ite++)
- {
- cout<<*ite<<" ";
- }
- cout<<endl;
- }
- void Create(vector<int>& v)
- {
- srand((unsigned int)time(NULL));
- v.resize(N);
- for(int i=0;i<N;i++)
- v[i]=rand()%100;
- }
- // bool cmp(int arg1,int arg2)
- // {
- // return arg1<arg2;
- // }
- void sort1(vector<int> v)
- {
- sort(v.begin(),v.end());
- cout<<"after sort funtion:\n";
- print(v);
- }
- void sort2(vector<int> v)
- {
- stable_sort(v.begin(),v.end());
- cout<<"after stable_sort funtion:\n";
- print(v);
- }
- void sort3(vector<int> v)
- {
- partial_sort(v.begin(),v.begin()+v.size()/2,v.end()); //对前半部分排序
- cout<<"after partial_sort funtion:\n";
- print(v);
- }
- void sort4(vector<int> v)
- {
- vector<int> temp;
- temp.resize(v.size());
- partial_sort_copy(v.begin(),v.end(),temp.begin(),temp.end()); //复制并排序
- cout<<"after partial_sort_copy funtion:\n";
- print(temp);
- }
- void main()
- {
- vector<int> v;
- Create(v);
- cout<<"before sort:\n";
- print(v);
- sort1(v);
- sort2(v);
- sort3(v);
- sort4(v);
- }
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <algorithm>
- #include <stdlib.h>
- #include <time.h>
- #include <VECTOR>
- using namespace std;
- const int N=10;
- void print(const vector<int>& v)
- {
- vector<int>::const_iterator ite=v.begin();
- for(;ite!=v.end();ite++)
- {
- cout<<*ite<<" ";
- }
- cout<<endl;
- }
- void Create(vector<int>& v)
- {
- srand((unsigned int)time(NULL));
- v.resize(N);
- for(int i=0;i<N;i++)
- v[i]=rand()%100;
- }
- // bool cmp(int arg1,int arg2)
- // {
- // return arg1<arg2;
- // }
- void sort1(vector<int> v)
- {
- sort(v.begin(),v.end());
- cout<<"after sort funtion:\n";
- print(v);
- }
- void sort2(vector<int> v)
- {
- stable_sort(v.begin(),v.end());
- cout<<"after stable_sort funtion:\n";
- print(v);
- }
- void sort3(vector<int> v)
- {
- partial_sort(v.begin(),v.begin()+v.size()/2,v.end()); //对前半部分排序
- cout<<"after partial_sort funtion:\n";
- print(v);
- }
- void sort4(vector<int> v)
- {
- vector<int> temp;
- temp.resize(v.size());
- partial_sort_copy(v.begin(),v.end(),temp.begin(),temp.end()); //复制并排序
- cout<<"after partial_sort_copy funtion:\n";
- print(temp);
- }
- void main()
- {
- vector<int> v;
- Create(v);
- cout<<"before sort:\n";
- print(v);
- sort1(v);
- sort2(v);
- sort3(v);
- sort4(v);
- }
6 生成全排列
next_permutation()的原型如下:
template<class BidirectionalIterator>
bool next_permutation(
BidirectionalIterator _First,
BidirectionalIterator _Last
);
template<class BidirectionalIterator, class BinaryPredicate>
bool next_permutation(
BidirectionalIterator _First,
BidirectionalIterator _Last,
BinaryPredicate _Comp
);
两个重载函数,第二个带谓词参数_Comp,其中只带两个参数的版本,默认谓词函数为"小于".,返回值为bool类型
示例代码如下:
[cpp] view
plaincopyprint?
- #include <iostream>
- #include <algorithm>
- using namespace std;
- void permutation(char* str,int length)
- {
- sort(str,str+length);
- do
- {
- for(int i=0;i<length;i++)
- cout<<str[i];
- cout<<endl;
- }while(next_permutation(str,str+length));
- }
- int main(void)
- {
- char str[] = "acb";
- cout<<str<<"所有全排列的结果为:"<<endl;
- permutation(str,3);
- system("pause");
- return 0;
- }