常用STL容器及算法举例

一 常用容器举例 

1 vector:

       vector类似于动态数组,直接访问元素,从后面快速插入或者删除,示例代码如下:

  1. #include <iostream>   
  2. #include <vector>//包含vector   
  3. using namespace std;//指定命名空间   
  4.   
  5. int main()  
  6. {  
  7.     cout<<"----------vector test-----------"<<endl;  
  8.       
  9.     //定义一个vector   
  10.     vector <int> vect;  
  11.     vector <int> vect1(12);//12个int类型元素,每个元素的初始值均为0   
  12.     vector <int> vect2(12,9);//12个int,初试值均为9   
  13.       
  14.   
  15.     //使用数组初始化vector   
  16.     int a[]={0,1,2,3,4,5,6,7,8,9,0};  
  17.     //vector <数据类型> <容器名> (<开始地址>,<结束地址的下一个地址> )。执行过vt中元素为1,2,3   
  18.     vector <int> vt(a+1,a+4);  
  19.     //在尾部压入3个值   
  20.     vt.push_back(1);  
  21.     vt.push_back(2);  
  22.     vt.push_back(3);  
  23.   
  24.     //定义迭代器iterator   
  25.     vector <int>::iterator iter=vt.begin();//起始地址   
  26.     vector <int>::iterator iter_end=vt.end();//结束地址,两个地址都是指针类型   
  27.     //遍历vt   
  28.     for(;iter!=iter_end;iter++)  
  29.     {  
  30.         cout<<*iter<<endl;  
  31.     }  
  32.       
  33.     //弹出一个元素   
  34.     vt.pop_back();  
  35.       
  36.     //以下两行重新获得起始和结尾地址   
  37.     iter=vt.begin();  
  38.     iter_end=vt.end();  
  39.     cout<<"----------executed pop_back------"<<endl;  
  40.     for(;iter!=iter_end;iter++)  
  41.     {  
  42.         cout<<*iter<<endl;  
  43.     }  
  44.   
  45.     //插入元素   
  46.     cout<<"----------insert into------------"<<endl;  
  47.     //插入格式:vector.insert(<起始地址>,<插入的数量>,<元素值>);如果插入的数量为1,则第二个参数可以被省略   
  48.     vt.insert(vt.begin()+1,3,9);  
  49.     iter=vt.begin();  
  50.     iter_end=vt.end();  
  51.     for(;iter!=iter_end;iter++)  
  52.     {  
  53.         cout<<*iter<<endl;  
  54.     }  
  55.       
  56.     //删除元素   
  57.     cout<<"----------erase-------------------"<<endl;  
  58.     //删除格式1为:vector.erase(<删除元素的地址>);   
  59.     //删除格式2为:vector.erase(<删除元素的起始地址>,<终止地址>);   
  60.     iter=vt.begin();  
  61.     iter_end=vt.end();  
  62.     vt.erase(iter+1,iter_end);//删除第二个到最后一个的元素   
  63.     iter_end=vt.end();  
  64.     for(;iter!=iter_end;iter++)  
  65.     {  
  66.         cout<<*iter<<endl;  
  67.     }  
  68.     return 1;  
  69. }  
#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 为双向链表,可以从任何地方插入或者删除的,其示例代码如下:

  1. #include <iostream>   
  2. #include <list>   
  3. using namespace std;  
  4.   
  5. void main()  
  6. {  
  7.     list<int> c1;  
  8.     c1.push_back(1);//从尾部push数据(结点)到list中    
  9.     c1.push_back(2);   
  10.     c1.push_back(3);  
  11.     c1.push_back(4);  
  12.       
  13.     c1.push_front(0);//从头部push数据(结点)到list中    
  14.       
  15.     c1.pop_back();//从尾部pop数据(结点)出去    
  16.     int& i = c1.back();//获取list中尾部数据(结点)    
  17.     const int& ii = c1.front();//获取list中头部 数据(结点)   
  18.       
  19.       
  20.     cout << "The last integer of c1 is " << i << endl;  
  21.     cout << "The front interger of c1 is " << ii << endl;  
  22.       
  23.     cout << "for循环读出数据举例:" << endl;  
  24.     //循环遍历数据举例   
  25.     list<int>::iterator it; //定义遍历指示器(类似于int i=0)    
  26.     for(it = c1.begin() ; it != c1.end() ;it++)  
  27.     {  
  28.         cout << *it << endl;  
  29.     }  
  30.     system("pause");  
  31. }  
#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。

示例代码如下:

  1. /*deque: 是一个double-ended queue, 
  2.     1)支持随即存取,也就是[]操作符, 
  3.     2)支持两端操作,push(pop)-back(front),在两端操作上与list效率差不多 
  4.  
  5.     因此在实际使用时,如何选择这三个容器中哪一个,应根据你的需要而定,一般应遵循下面的原则:  
  6.     1、如果你需要高效的随即存取,而不在乎插入和删除的效率,使用vector  
  7.     2、如果你需要大量的插入和删除,而不关心随即存取,则应使用list  
  8.     3、如果你需要随即存取,而且关心两端数据的插入和删除,则应使用deque。 
  9. */  
  10.   
  11. #include <iostream>   
  12. #include <deque>   
  13. using namespace std;  
  14.   
  15. void printDeque(const deque<int>& d)  
  16. {  
  17.     cout<<"\n使用下标:\n";  
  18.     for (unsigned int i = 0; i < d.size(); i++)  
  19.     {  
  20.     cout<<"d["<<i<<"] = "<<d[i]<<", ";  
  21.     }  
  22.   
  23.   
  24.     cout<<"\n使用迭代器\n";  
  25.     deque<int>::const_iterator iter = d.begin();  
  26.     for (;iter != d.end(); iter ++)  
  27.     {  
  28.     cout<<"d["<<iter-d.begin()<<"] = "<<(*iter)<<", ";  
  29.     }  
  30.     cout<<endl;  
  31. }  
  32.   
  33. void main()  
  34. {  
  35. //创建deque   
  36. deque<int> d1;                          //创建一个没有任何元素的deque对象   
  37. deque<int> d2(10);                      //创建一个具有10个元素的deque对象,每个元素值为默认   
  38. deque<double> d3(10, 5.5);              //创建一个具有10个元素的deque对象,每个元素的初始值为5.5   
  39. deque<double> d4(d3);                   //通过拷贝一个deque对象的元素值, 创建一个新的deque对象   
  40.   
  41. //初始化赋值:同vector一样,使用尾部插入函数push_back()   
  42. for (int i = 1; i < 6 ; i++)  
  43.    d1.push_back(i*10);  
  44.   
  45.   
  46. //遍历元素: 1-下标方式 2-迭代器方式 反向遍历(略)   
  47. cout<<"printDeque(d1) : "<<endl;  
  48. printDeque(d1);  
  49.   
  50. //元素插入:尾部插入用push_back(),头部插入用push_front(),其它位置插入用insert(&pos, elem)   
  51. cout<<"d1.push_front(100): "<<endl;  
  52. d1.push_front(100);  
  53. printDeque(d1);  
  54. cout<<"d1.insert(d1.begin()+3, 200): "<<endl; //支持随机存取(即[]操作符),所以begin()可以+3   
  55. d1.insert(d1.begin()+2,200);  
  56. printDeque(d1);  
  57.   
  58. //元素删除 尾部删除用pop_back();头部删除用pop_front();    
  59. //任意迭代位置或迭代区间上的元素删除用erase(&pos)/erase(&first, &last);删除所有元素用clear();   
  60. cout<<"d1.pop_front(): "<<endl;  
  61. d1.pop_front();  
  62. printDeque(d1);  
  63.   
  64. cout<<"d1.erase(d1.begin()+1): "<<endl;  
  65. d1.erase(d1.begin()+1); //删除第2个元素d1[1]   
  66. printDeque(d1);  
  67.   
  68. cout<<"d1.erase(d1.begin(), d1.begin() + 2) = "<<endl;  
  69. d1.erase(d1.begin(), d1.begin() + 2);  
  70. printDeque(d1);  
  71.   
  72. cout<<"d1.clear() :"<<endl;  
  73. d1.clear();  
  74. printDeque(d1);  
  75.   
  76.   
  77.   
  78. }  
/*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)用 vectordeque实现,比用list实现性能好

(4)stack是后进先出的数据结构,

(5)只能插入、删除、访问栈顶的元素的操作push:     插入元素pop:       弹出元素      top: 返回栈顶元素的引用

测试代码如下:

  1. <SPAN style="FONT-SIZE: 16px">#include <iostream>  
  2. #include <Stack>   
  3. using namespace std;  
  4.   
  5. void main()  
  6. {  
  7.     stack<double> s;//可以是各种数据类型;   
  8.     forint i=0; i < 10; i++ )  
  9.         s.push(i);  
  10.     while(!s.empty())  
  11.     {  
  12.         printf("%lf\n",s.top());  
  13.         s.pop();  
  14.     }  
  15.     cout << "the size of  s: " << s.size() << endl;  
  16. }  
  17. </SPAN>  
#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;
}

5 deque

可以用 listdeque实现,缺省情况下用deque实现

          template<class T, class Cont = deque<T>>

           class queue {  …  };

 FIFO先进先出的数据结构,也有push,pop,top函数,但是push发生在队尾,pop,top发生在队头,

示例代码如下:


  1. /************************************************************************/  
  2. /*  
  3.  
  4. 详细用法: 
  5. 定义一个queue的变量     queue<Type> M 
  6. 查看是否为空范例        M.empty()    是的话返回1,不是返回0; 
  7. 从已有元素后面增加元素   M.push() 
  8. 输出现有元素的个数      M.size() 
  9. 显示第一个元素          M.front() 
  10. 显示最后一个元素        M.back() 
  11. 清除第一个元素          M.pop() 
  12.                                                                      */  
  13. /************************************************************************/  
  14.   
  15. #include <iostream>   
  16. #include <queue>   
  17. #include <assert.h>   
  18.   
  19. using namespace std;  
  20.   
  21. int main()  
  22. {  
  23.     queue <int> myQ;  
  24.     int i;  
  25.     cout<< "现在 queue 是否 empty? "<< myQ.empty() << endl;   
  26.       
  27.     for( i =0; i<10 ; i++)  
  28.     {  
  29.         myQ.push(i);  
  30.     }  
  31.     for( i=0; i<myQ.size(); i++)  
  32.     {  
  33.         printf("myQ.size():%d\n",myQ.size());  
  34.         cout << myQ.front()<<endl;  
  35.         myQ.pop();  
  36.     }  
  37.       
  38.     system("PAUSE");   
  39.       
  40.     return 0;  
  41. }  
/************************************************************************/
/* 

详细用法:
定义一个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()在序列中统计与某谓词匹配的次数

示例代码如下:

  1. #include <iostream>   
  2. #include <algorithm>   
  3. #include <functional>   
  4. #include <string>   
  5. #include <vector>   
  6.   
  7. using namespace std;  
  8.   
  9.   
  10. void CountFuc()  
  11. {  
  12.     const int VECTOR_SIZE = 8 ;  
  13.       
  14.     // Define a template class vector of strings   
  15.     typedef vector<string > StringVector ;  
  16.       
  17.     //Define an iterator for template class vector of strings   
  18.     typedef StringVector::iterator StringVectorIt ;  
  19.       
  20.     StringVector NamesVect(VECTOR_SIZE) ;   //vector containing names   
  21.       
  22.     string value("Sea") ;  // stores the value used   
  23.     // to count matching elements   
  24.       
  25.     StringVectorIt start, end, it ;  
  26.       
  27.     int result = 0 ;   // stores count of elements   
  28.     // that match value.   
  29.       
  30.     // Initialize vector NamesVect   
  31.     NamesVect[0] = "She" ;  
  32.     NamesVect[1] = "Sells" ;  
  33.     NamesVect[2] = "Sea" ;  
  34.     NamesVect[3] = "Shells" ;  
  35.     NamesVect[4] = "by" ;  
  36.     NamesVect[5] = "the" ;  
  37.     NamesVect[6] = "Sea" ;  
  38.     NamesVect[7] = "Shore" ;  
  39.       
  40.     start = NamesVect.begin() ;   // location of first   
  41.     // element of NamesVect   
  42.       
  43.     end = NamesVect.end() ;       // one past the location   
  44.     // last element of NamesVect   
  45.       
  46.     // print content of NamesVect   
  47.     cout << "NamesVect { " ;  
  48.     for(it = start; it != end; it++)  
  49.         cout << *it << " " ;  
  50.     cout << " }\n" << endl ;  
  51.       
  52.     // Count the number of elements in the range [first, last +1)   
  53.     // that match value.   
  54.     result = count(start, end, value) ;  
  55.       
  56.     // print the count of elements that match value   
  57.     cout << "Number of elements that match \"Sea\" = "  
  58.         << result << endl  ;  
  59. }  
  60.   
  61.   
  62. int MatchFirstChar( const string& str)  
  63. {  
  64.     string s("S") ;  
  65.     return s == str.substr(0,1) ;  
  66. }  
  67.   
  68.   
  69. void CountIfFuc()  
  70. {  
  71.     const int VECTOR_SIZE = 8 ;  
  72.       
  73.     // Define a template class vector of strings   
  74.     typedef vector<string > StringVector ;  
  75.       
  76.     //Define an iterator for template class vector of strings   
  77.     typedef StringVector::iterator StringVectorIt ;  
  78.       
  79.     StringVector NamesVect(VECTOR_SIZE) ;   //vector containing names   
  80.       
  81.     StringVectorIt start, end, it ;  
  82.       
  83.     int result = 0 ;   // stores count of elements   
  84.     // that match value.   
  85.       
  86.     // Initialize vector NamesVect   
  87.     NamesVect[0] = "She" ;  
  88.     NamesVect[1] = "Sells" ;  
  89.     NamesVect[2] = "Sea" ;  
  90.     NamesVect[3] = "Shells" ;  
  91.     NamesVect[4] = "by" ;  
  92.     NamesVect[5] = "the" ;  
  93.     NamesVect[6] = "Sea" ;  
  94.     NamesVect[7] = "Shore" ;  
  95.       
  96.     start = NamesVect.begin() ;   // location of first   
  97.     // element of NamesVect   
  98.       
  99.     end = NamesVect.end() ;       // one past the location   
  100.     // last element of NamesVect   
  101.       
  102.     // print content of NamesVect   
  103.     cout << "NamesVect { " ;  
  104.     for(it = start; it != end; it++)  
  105.         cout << *it << " " ;  
  106.     cout << " }\n" << endl ;  
  107.       
  108.     // Count the number of elements in the range [first, last +1)   
  109.     // that start with letter 'S'   
  110.     result = count_if(start, end, MatchFirstChar) ;  
  111.       
  112.     // print the count of elements that start with letter 'S'   
  113.     cout << "Number of elements that start with letter \"S\" = "  
  114.         << result << endl  ;  
  115. }  
  116.   
  117.   
  118. void main()  
  119. {  
  120.     CountFuc();  
  121.     CountIfFuc();  
  122. }  
#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     在序列中找出符合某谓词的第一个元素

示例代码如下:

  1. #include <algorithm>   
  2. #include <iostream>   
  3.   
  4. using namespace std;  
  5.   
  6.   
  7. void FindFuc()  
  8. {  
  9.     const int ARRAY_SIZE = 8 ;  
  10.     int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;  
  11.       
  12.     int *location ;   // stores the position of the first   
  13.     // matching element.   
  14.       
  15.     int i ;  
  16.       
  17.     int value = 4 ;  
  18.       
  19.     // print content of IntArray   
  20.     cout << "IntArray { " ;  
  21.     for(i = 0; i < ARRAY_SIZE; i++)  
  22.         cout << IntArray[i] << ", " ;  
  23.     cout << " }" << endl ;  
  24.       
  25.     // Find the first element in the range [first, last + 1)   
  26.     // that matches value.   
  27.     location = find(IntArray, IntArray + ARRAY_SIZE, value) ;  
  28.       
  29.     //print the matching element if any was found   
  30.     if (location != IntArray + ARRAY_SIZE)  // matching element found   
  31.         cout << "First element that matches " << value  
  32.         << " is at location " << location - IntArray << endl;  
  33.     else                                    // no matching element was   
  34.         // found   
  35.         cout << "The sequence does not contain any elements"  
  36.         << " with value " << value << endl ;  
  37. }  
  38.   
  39. int IsOdd( int n)  
  40. {  
  41.     return n % 2 ;  
  42. }  
  43.   
  44.   
  45. void FindIfFuc()  
  46. {  
  47.     const int ARRAY_SIZE = 8 ;  
  48.     int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;  
  49.     int *location ;   // stores the position of the first   
  50.     // element that is an odd number   
  51.     int i ;  
  52.       
  53.     // print content of IntArray   
  54.     cout << "IntArray { " ;  
  55.     for(i = 0; i < ARRAY_SIZE; i++)  
  56.         cout << IntArray[i] << ", " ;  
  57.     cout << " }" << endl ;  
  58.       
  59.     // Find the first element in the range [first, last -1 ]   
  60.     // that is an odd number   
  61.     location = find_if(IntArray, IntArray + ARRAY_SIZE, IsOdd) ;  
  62.       
  63.     //print the location of the first element   
  64.     // that is an odd number   
  65.     if (location != IntArray + ARRAY_SIZE)  // first odd element found   
  66.         cout << "First odd element " << *location  
  67.         << " is at location " << location - IntArray << endl;  
  68.     else         // no odd numbers in the range   
  69.         cout << "The sequence does not contain any odd numbers"  
  70.         << endl ;  
  71.   
  72. }  
  73.   
  74.   
  75. void main()  
  76. {  
  77.     FindFuc();  
  78.     FindIfFuc();  
  79. }  
#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操作

示例代码如下:

  1. #include <iostream>   
  2. #include <vector>   
  3. #include <algorithm>   
  4.   
  5. using namespace std;  
  6.   
  7.   
  8. // prints the cube of integer n   
  9. void PrintCube(int n)  
  10. {  
  11.     cout << n * n * n << " " ;  
  12. }  
  13.   
  14. void main()  
  15. {  
  16.     const int VECTOR_SIZE = 8 ;  
  17.       
  18.     // Define a template class vector of integers   
  19.     typedef vector<int > IntVector ;  
  20.       
  21.     //Define an iterator for template class vector of integer   
  22.     typedef IntVector::iterator IntVectorIt ;  
  23.       
  24.     IntVector Numbers(VECTOR_SIZE) ;   //vector containing numbers   
  25.       
  26.     IntVectorIt start, end, it ;  
  27.       
  28.     int i ;  
  29.       
  30.     // Initialize vector Numbers   
  31.     for (i = 0; i < VECTOR_SIZE; i++)  
  32.         Numbers[i] = i + 1 ;  
  33.       
  34.     start = Numbers.begin() ;   // location of first   
  35.     // element of Numbers   
  36.       
  37.     end = Numbers.end() ;       // one past the location   
  38.     // last element of Numbers   
  39.       
  40.     // print content of Numbers   
  41.     cout << "Numbers { " ;  
  42.     for(it = start; it != end; it++)  
  43.         cout << *it << " " ;  
  44.     cout << " }\n" << endl ;  
  45.       
  46.     // for each element in the range [first, last)   
  47.     // print the cube of the element   
  48.     for_each(start, end, PrintCube) ;  
  49.     cout << "\n\n" ;  
  50. }  
#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指向最后的重复元素,所以用它来删除重复元素时必须先排序

示例代码如下:

  1. #include <iostream>   
  2. #include <algorithm>   
  3. #include <vector>   
  4. #include <string>   
  5. using namespace std;  
  6.   
  7.   
  8. void main()  
  9. {  
  10.     string str;  
  11.     vector<string> words;  
  12.     while(cin>>str&&str!="#")  
  13.     {  
  14.         words.push_back(str);  
  15.     }  
  16.       
  17.     sort(words.begin(),words.end());  
  18.     vector<string>::iterator end_unique =  
  19.         unique(words.begin(),words.end());  
  20.     words.erase(end_unique,words.end());  
  21.       
  22.       
  23.     vector<string> ::iterator ite=words.begin();  
  24.     for(;ite!=words.end();ite++)  
  25.     {  
  26.         cout<<*ite<<"   ";  
  27.     }  
  28.       
  29.     cout<<endl;  
  30. }  
#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 对给定区间复制并排序

示例代码如下:

  1. #include <iostream>   
  2. #include <algorithm>   
  3. #include <stdlib.h>   
  4. #include <time.h>   
  5. #include <VECTOR>   
  6. using namespace std;  
  7.   
  8.   
  9. const int N=10;  
  10.   
  11. void print(const vector<int>& v)  
  12. {  
  13.     vector<int>::const_iterator ite=v.begin();  
  14.     for(;ite!=v.end();ite++)  
  15.     {  
  16.         cout<<*ite<<"  ";  
  17.     }  
  18.   
  19.     cout<<endl;  
  20. }  
  21.   
  22. void Create(vector<int>& v)  
  23. {  
  24.     srand((unsigned int)time(NULL));  
  25.     v.resize(N);  
  26.     for(int i=0;i<N;i++)  
  27.         v[i]=rand()%100;  
  28. }  
  29.   
  30.   
  31. // bool cmp(int arg1,int arg2)   
  32. // {   
  33. //  return arg1<arg2;   
  34. // }   
  35.   
  36.   
  37. void sort1(vector<int> v)  
  38. {  
  39.     sort(v.begin(),v.end());  
  40.     cout<<"after sort funtion:\n";  
  41.     print(v);  
  42. }  
  43.   
  44. void sort2(vector<int> v)  
  45. {  
  46.     stable_sort(v.begin(),v.end());  
  47.     cout<<"after stable_sort funtion:\n";  
  48.     print(v);  
  49. }  
  50.   
  51. void sort3(vector<int> v)  
  52. {  
  53.     partial_sort(v.begin(),v.begin()+v.size()/2,v.end()); //对前半部分排序   
  54.     cout<<"after partial_sort funtion:\n";  
  55.     print(v);  
  56. }  
  57.   
  58. void sort4(vector<int> v)  
  59. {  
  60.     vector<int> temp;  
  61.     temp.resize(v.size());  
  62.     partial_sort_copy(v.begin(),v.end(),temp.begin(),temp.end()); //复制并排序   
  63.     cout<<"after partial_sort_copy funtion:\n";  
  64.     print(temp);  
  65. }  
  66.   
  67.   
  68. void main()  
  69. {  
  70.     vector<int> v;  
  71.   
  72.     Create(v);  
  73.     cout<<"before sort:\n";  
  74.     print(v);  
  75.   
  76.     sort1(v);  
  77.     sort2(v);  
  78.     sort3(v);  
  79.     sort4(v);  
  80. }  
#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类型

示例代码如下:

  1. #include <iostream>   
  2. #include <algorithm>   
  3. using namespace std;  
  4.   
  5. void permutation(char* str,int length)  
  6. {  
  7.     sort(str,str+length);  
  8.     do  
  9.     {  
  10.         for(int i=0;i<length;i++)  
  11.             cout<<str[i];  
  12.         cout<<endl;  
  13.     }while(next_permutation(str,str+length));  
  14.       
  15. }  
  16. int main(void)  
  17. {  
  18.     char str[] = "acb";  
  19.     cout<<str<<"所有全排列的结果为:"<<endl;  
  20.     permutation(str,3);  
  21.     system("pause");  
  22.     return 0;  
  23. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值