vector与算法

http://classfoo.com/ccby/article/cIBahI


                                                                                                    <algorithm> 头文件中包含大量与 vector 相关的算法,这些算法同样适用于其它容器,比如 std::list 等。

  • 相关函数有:

    std::sort std::partial_sort
    std::stable_sort  

    普通排序

    Example 1
        
        
    1. #include <vector>
    2. #include <algorithm>
    3. #include <functional> // For greater<int>()
    4. #include <iostream>
    5.  
    6. namespace ClassFoo{
    7. // 返回第一个元素是否比第二个元素大
    8. bool UDgreater ( int elem1, int elem2 )
    9. {
    10. return elem1 > elem2;
    11. }
    12.  
    13. void NormalSort1() {
    14.  
    15. using namespace std;
    16. vector <int> foo;
    17. vector <int>::iterator Iter1;
    18.  
    19. int i;
    20. for ( i = 0 ; i <= 5 ; i++ )
    21. {
    22. foo.push_back( 2 * i );
    23. }
    24.  
    25. int ii;
    26. for ( ii = 0 ; ii <= 5 ; ii++ )
    27. {
    28. foo.push_back( 2 * ii + 1 );
    29. }
    30.  
    31. cout << "Original vector foo = ( " ;
    32. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    33. cout << *Iter1 << " ";
    34. cout << ")" << endl;
    35.  
    36.  
    37. // 按升序排序,使用默认的二元谓词函数
    38. sort( foo.begin( ), foo.end( ) );
    39. cout << "Sorted vector foo = ( " ;
    40. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    41. cout << *Iter1 << " ";
    42. cout << ")" << endl;
    43.  
    44. // 按降序排序,提供二元谓词函数
    45. sort( foo.begin( ), foo.end( ), greater<int>( ) );
    46. cout << "Resorted (greater) vector foo = ( " ;
    47. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    48. cout << *Iter1 << " ";
    49. cout << ")" << endl;
    50.  
    51. // 使用自定义的二元谓词函数
    52. sort( foo.begin( ), foo.end( ), UDgreater );
    53. cout << "Resorted (UDgreater) vector foo = ( " ;
    54. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    55. cout << *Iter1 << " ";
    56. cout << ")" << endl;
    57. }
    58. }
    59.  
    60. int main()
    61. {
    62. ClassFoo::NormalSort1();
    63. return 0;
    64. }

    输出

    Original vector foo = ( 0 2 4 6 8 10 1 3 5 7 9 11 )
    Sorted vector foo = ( 0 1 2 3 4 5 6 7 8 9 10 11 )
    Resorted (greater) vector foo = ( 11 10 9 8 7 6 5 4 3 2 1 0 )
    Resorted (UDgreater) vector foo = ( 11 10 9 8 7 6 5 4 3 2 1 0 )

    Example 2

    使用函数对象。

        
        
    1. #include <vector>
    2. #include <algorithm>// for generate、partial_sort
    3. #include <functional>
    4. #include <iostream>
    5. #include <cstdlib> // std::rand, std::srand
    6. #include <ctime> // std::time
    7.  
    8. namespace ClassFoo{
    9.  
    10. struct {
    11. bool operator()(int a, int b)
    12. {
    13. return a < b;
    14. }
    15. } FooLess;
    16.  
    17. void PrintIntVector(std::vector<int>& foo) {
    18. std::vector <int>::iterator Iter1;
    19. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    20. std::cout << *Iter1 << " ";
    21. std::cout << std::endl;
    22. }
    23.  
    24. void NormalSort2() {
    25. using namespace std;
    26. vector<int> foo;
    27. int i;
    28. for ( i = 0 ; i <= 5 ; i++ )
    29. {
    30. foo.push_back( 2 * i );
    31. }
    32.  
    33. int ii;
    34. for ( ii = 0 ; ii <= 5 ; ii++ )
    35. {
    36. foo.push_back( 2 * ii + 1 );
    37. }
    38. PrintIntVector(foo);
    39. std::sort(foo.begin(), foo.end(), FooLess);
    40. PrintIntVector(foo);
    41. }
    42. }
    43.  
    44. int main(void)
    45. {
    46. ClassFoo::NormalSort2();
    47. return 0;
    48. }

    输出

    0 2 4 6 8 10 1 3 5 7 9 11
    0 1 2 3 4 5 6 7 8 9 10 11

    Example 3 C++11

    使用 lambda 表达式。

        
        
    1. #include <vector>
    2. #include <algorithm> // for generate、partial_sort
    3. #include <functional>
    4. #include <iostream>
    5. #include <cstdlib> // std::rand, std::srand
    6. #include <ctime> // std::time
    7.  
    8. namespace ClassFoo{
    9.  
    10. void PrintIntVector(std::vector<int>& foo) {
    11. std::vector <int>::iterator Iter1;
    12. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    13. std::cout << *Iter1 << " ";
    14. std::cout << std::endl;
    15. }
    16.  
    17. void NormalSort3() {
    18. using namespace std;
    19. vector<int> foo;
    20. int i;
    21. for ( i = 0 ; i <= 5 ; i++ )
    22. {
    23. foo.push_back( 2 * i );
    24. }
    25.  
    26. int ii;
    27. for ( ii = 0 ; ii <= 5 ; ii++ )
    28. {
    29. foo.push_back( 2 * ii + 1 );
    30. }
    31. PrintIntVector(foo);
    32. std::sort(foo.begin(), foo.end(), [](int a, int b) {
    33. return b < a;
    34. });
    35. PrintIntVector(foo);
    36. }
    37. }
    38.  
    39. int main(void)
    40. {
    41. ClassFoo::NormalSort3();
    42. return 0;
    43. }

    输出

    0 2 4 6 8 10 1 3 5 7 9 11
    11 10 9 8 7 6 5 4 3 2 1 0

    部份排序(Partial Sort)

        
        
    1. #include <vector>
    2. #include <algorithm> // for generate、partial_sort
    3. #include <functional>
    4. #include <iostream>
    5. #include <cstdlib> // std::rand, std::srand
    6. #include <ctime> // std::time
    7.  
    8. namespace ClassFoo{
    9.  
    10. int RandomNumber () { return (std::rand()%100); }
    11.  
    12. void PartialSort1()
    13. {
    14. std::srand ( unsigned ( std::time(0) ) );
    15. std::vector<int> foo(15);
    16. std::generate(foo.begin(), foo.end(), RandomNumber);
    17. // 部份排序前七个元素
    18. std::partial_sort(foo.begin(), foo.begin() + 7, foo.end());
    19. }
    20. }
    21.  
    22. int main(void)
    23. {
    24. ClassFoo::PartialSort1();
    25. return 0;
    26. }

    稳定排序

    Example 1
        
        
    1. #include <vector>
    2. #include <algorithm>
    3. #include <functional> // For greater<int>( )
    4. #include <iostream>
    5.  
    6. namespace ClassFoo{
    7. // 返回第一个元素是否比第二个元素大
    8. bool UDgreater(int elem1, int elem2 )
    9. {
    10. return elem1 > elem2;
    11. }
    12. void StableSort1() {
    13. using namespace std;
    14. vector <int> v1;
    15. vector <int>::iterator Iter1;
    16.  
    17. int i;
    18. for ( i = 0 ; i <= 5 ; i++ )
    19. {
    20. v1.push_back( 2 * i );
    21. }
    22.  
    23. for ( i = 0 ; i <= 5 ; i++ )
    24. {
    25. v1.push_back( 2 * i );
    26. }
    27.  
    28. for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
    29. cout << *Iter1 << " ";
    30. cout << endl;
    31.  
    32. // 按升序排序,使用默认的二元谓词函数
    33. stable_sort(v1.begin( ), v1.end( ) );
    34. for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
    35. cout << *Iter1 << " ";
    36. cout << endl;
    37.  
    38. // 按降序排序,提供二元谓词函数
    39. stable_sort(v1.begin( ), v1.end( ), greater<int>( ) );
    40. for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
    41. cout << *Iter1 << " ";
    42. cout << endl;
    43.  
    44. // 按降序排序,使用自定义的二元谓词函数
    45. stable_sort(v1.begin( ), v1.end( ), UDgreater );
    46. for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
    47. cout << *Iter1 << " ";
    48. cout << endl;
    49. }
    50. }
    51. int main( )
    52. {
    53. ClassFoo::StableSort1();
    54. return 0;
    55. }

    输出:

    0 2 4 6 8 10 0 2 4 6 8 10
    0 0 2 2 4 4 6 6 8 8 10 10
    10 10 8 8 6 6 4 4 2 2 0 0
    10 10 8 8 6 6 4 4 2 2 0 0

  • 相关函数有:

    std::adjacent_find std::count
    std::count_if std::find
    std::find_if std::find_end
    std::find_first_of std::search
    std::search_n std::equal
    std::mismatch  
        
        
    1. #include <iostream>
    2. #include <algorithm>
    3. #include <functional>
    4. #include <vector>
    5. // 用在此处是为了方便简洁, 在实际编程中慎用
    6. using namespace std;
    7. void main()
    8. {
    9. int iarray[]={0,1,2,3,4,5,6,6,6,7,8};
    10. vector<int> foo1(iarray,iarray+sizeof(iarray)/sizeof(int));
    11. int iarray1[]={6,6};
    12. vector<int> foo2(iarray1,iarray1+sizeof(iarray1)/sizeof(int));
    13. int iarray2[]={5,6};
    14. vector<int> foo3(iarray2,iarray2+sizeof(iarray2)/sizeof(int));
    15. int iarray3[]={0,1,2,3,4,5,7,7,7,9,7};
    16. vector<int> foo4(iarray3,iarray3+sizeof(iarray3)/sizeof(int));
    17.  
    18. //找出foo1之中相邻元素值相等的第一个元素
    19. cout<<*adjacent_find(foo1.begin(),foo1.end())<<endl;
    20.  
    21. //找出foo1之中元素值为6的元素个数
    22. cout<<count(foo1.begin(),foo1.end(),6)<<endl;
    23.  
    24. //找出foo1之中小于7的元素个数
    25. cout<<count_if(foo1.begin(),foo1.end(),bind2nd(less<int>(),7))<<endl;
    26.  
    27. //找出foo1之中元素值为4的第一个元素所在位置的元素
    28. cout<<*find(foo1.begin(),foo1.end(),4)<<endl;
    29.  
    30. //找出foo1之中大于2的第一个元素所在位置的元素
    31. cout<<*find_if(foo1.begin(),foo1.end(),bind2nd(greater<int>(),2))
    32. <<endl;
    33.  
    34. //找出foo1之中子序列foo2所出现的最后一个位置,再往后3个位置的元素
    35. cout<<*(find_end(foo1.begin(),foo1.end(),foo2.begin(),
    36. foo2.end())+3)<<endl;
    37.  
    38. //找出foo1之中子序列foo2所出现的第一个位置,再往后3个位置的元素
    39. cout<<*(find_first_of(foo1.begin(),foo1.end(),foo2.begin(),
    40. foo2.end())+3)<<endl;
    41.  
    42. //子序列foo3在foo1中出现的起点位置元素
    43. cout<<*search(foo1.begin(),foo1.end(),foo3.begin(),foo3.end())
    44. <<endl;
    45.  
    46. //查找连续出现3个6的起点位置元素
    47. cout<<*search_n(foo1.begin(),foo1.end(),3,6,equal_to<int>())<<endl;
    48.  
    49. //判断两个区间foo1和foo4相等否(0为假,1为真)
    50. cout << equal(foo1.begin(), foo1.end(), foo4.begin()) << endl;
    51.  
    52. //查找区间foo4在foo1中不匹配点的位置
    53. pair<std::vector<int>::iterator,std::vector<int>::iterator>result=
    54. mismatch(foo1.begin(),foo1.end(),foo4.begin());
    55. cout<< result.first - foo1.begin() << endl;
    56. }

    输出:

    6
    3
    9
    4
    3
    8
    7
    5
    6
    0
    6

  • 相关函数有:

    std::lower_bound std::upper_bound
    std::equal_range std::binary_search
    Example 1
        
        
    1. #include <vector>
    2. #include <algorithm> // for lower_bound()、greater<int>()
    3. #include <functional>
    4. #include <iostream>
    5.  
    6. // 用在此处是为了方便简洁, 在实际编程中慎用
    7. using namespace std;
    8.  
    9. // 返回elem1的绝对值是否比elem2的绝对值小
    10. bool mod_lesser(int elem1, int elem2)
    11. {
    12. if(elem1 < 0)
    13. elem1 = - elem1;
    14. if(elem2 < 0)
    15. elem2 = - elem2;
    16. return (elem1 < elem2);
    17. }
    18.  
    19. int main(void)
    20. {
    21. vector <int> foo1;
    22. vector <int>::iterator Iter1, Result1;
    23. int i, j;
    24.  
    25. // 插入数据
    26. for(i = -3; i <= 6; i++)
    27. foo1.push_back(i);
    28. for(j =-5; j <= 2; j++)
    29. foo1.push_back(j);
    30.  
    31. cout<<"操作: sort(foo1.begin(), foo1.end())"<< endl;
    32. sort(foo1.begin(), foo1.end());
    33. cout<<"使用默认的二元谓词“是否小于”排序后的结果:";
    34. for(Iter1 = foo1.begin(); Iter1 != foo1.end(); Iter1++)
    35. cout<<*Iter1<<" ";
    36. cout<<endl;
    37.  
    38. vector <int> foo2(foo1);
    39. vector <int>::iterator Iter2, Result2;
    40. cout<<"操作: sort(foo2.begin(), foo2.end(), greater<int>())"<<endl;
    41. sort(foo2.begin(), foo2.end(), greater<int>());
    42. cout<<"使用二元谓词“是否大于”排序后的结果:";
    43. for(Iter2 = foo2.begin(); Iter2 != foo2.end(); Iter2++)
    44. cout<<*Iter2<<" ";
    45. cout<<endl;
    46.  
    47. vector <int> foo3(foo1);
    48. vector <int>::iterator Iter3, Result3;
    49. cout<<"操作: sort(foo3.begin(), foo3.end(), mod_lesser)"<<endl;
    50. sort(foo3.begin(), foo3.end(), mod_lesser);
    51. cout<<"使用二元谓词 mod_lesser 排序后的结果:";
    52. for(Iter3 = foo3.begin(); Iter3 != foo3.end(); Iter3++)
    53. cout<<*Iter3<<" ";
    54. cout<<endl;
    55.  
    56. cout<<"操作: lower_bound(foo1.begin(), foo1.end(), 5)"<<endl;
    57. // 使用默认的二元谓词“是否小于”二分查找值为5的元素的位置
    58. Result1 = lower_bound(foo1.begin(), foo1.end(), 5);
    59. cout<<"在foo1中二分查找值为5的元素的位置对应的值(即5):"<<*Result1<<endl;
    60.  
    61. Result2 = lower_bound(foo2.begin(), foo2.end(), 5, greater<int>());
    62. // 使用二元谓词函数 greater<int>() 二分查找值为5的元素的位置
    63. cout<<"在foo1中二分查找值为5的元素的位置对应的值(即5):"<<*Result2<<endl;
    64.  
    65. cout<<"操作: lower_bound(foo3.begin(), foo3.end(), 5, mod_lesser)"<<endl;
    66. // 使用二元谓词函数 mod_lesser 二分查找值为5的元素的位置
    67. Result3 = lower_bound(foo3.begin(), foo3.end(), 5, mod_lesser);
    68. cout<<"在foo1中二分查找值为5的元素的位置对应的值(即5或-5):"<<*Result3<<endl;
    69.  
    70. return 0;
    71. }

    输出

    操作: sort(foo1.begin(), foo1.end())
    使用默认的二元谓词“是否小于”排序后的结果:-5 -4 -3 -3 -2 -2 -1 -1 0 0 1 1 2 2 3 4 5 6
    操作: sort(foo2.begin(), foo2.end(), greater<int>())
    使用二元谓词“是否大于”排序后的结果:6 5 4 3 2 2 1 1 0 0 -1 -1 -2 -2 -3 -3 -4 -5
    操作: sort(foo3.begin(), foo3.end(), mod_lesser)
    使用二元谓词 mod_lesser 排序后的结果:0 0 -1 -1 1 1 -2 -2 2 2 -3 -3 3 -4 4 -5 5 6
    操作: lower_bound(foo1.begin(), foo1.end(), 5)
    在foo1中二分查找值为5的元素的位置对应的值(即5):5
    在foo1中二分查找值为5的元素的位置对应的值(即5):5
    操作: lower_bound(foo3.begin(), foo3.end(), 5, mod_lesser)
    在foo1中二分查找值为5的元素的位置对应的值(即5或-5):-5

    Example 2
        
        
    1. #include <algorithm>
    2. #include <iostream>
    3. #include <iterator>
    4. #include <vector>
    5.  
    6. // 用在此处是为了方便简洁, 在实际编程中慎用
    7. using namespace std;
    8.  
    9. int main()
    10. {
    11. vector<int> v;
    12. vector<int>::iterator iter;
    13. pair<vector<int>::iterator, vector<int>::iterator> vecpair;
    14.  
    15. for(int i = 1; i<= 20; i++) {
    16. v.push_back(i%6);
    17. }
    18. sort(v.begin(), v.end());
    19. //将各个元素拷贝到输出流迭代器中
    20. copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
    21. cout << endl;
    22.  
    23. /* lower_bound */
    24. cout << "lower_bound function, value = 3: " << endl;
    25. iter = lower_bound(v.begin(), v.end(), 3);
    26. cout << " [first, iter] = ";
    27. copy(v.begin(), iter, ostream_iterator<int>(cout, " "));
    28. cout << endl;
    29. cout << " [iter, last] = ";
    30. copy(iter, v.end(), ostream_iterator<int>(cout, " "));
    31. cout << endl;
    32.  
    33. /* upper_bound */
    34. cout << "upper_bound function, value = 3: " << endl;
    35. iter = upper_bound(v.begin(), v.end(), 3);
    36. cout << " [first, iter] = ";
    37. copy(v.begin(), iter, ostream_iterator<int>(cout, " "));
    38. cout << endl;
    39. cout << " [iter, last] = ";
    40. copy(iter, v.end(), ostream_iterator<int>(cout, " "));
    41. cout << endl;
    42.  
    43. /* equal_range */
    44. cout << "euqual_range function value = 3: " << endl;
    45. vecpair = equal_range(v.begin(), v.end(), 3);
    46.  
    47. cout << " [vecpair->first, vecpair->second] = ";
    48. copy(vecpair.first, vecpair.second, ostream_iterator<int>(cout, " "));
    49. cout << endl;
    50.  
    51. /* binary_search */
    52. cout << "binary_search function value = 3: " << endl;
    53. cout << "3 is " << (binary_search(v.begin(), v.end(), 3) ? "": "not ") << " in array" << endl;
    54.  
    55. /* binary_search */
    56. cout << "binary_search function value = 6: " << endl;
    57. cout << "6 is " << (binary_search(v.begin(), v.end(), 6) ? "": "not ") << " in array" << endl;
    58.  
    59. }

    输出

    0 0 0 1 1 1 1 2 2 2 2 3 3 3 4 4 4 5 5 5
    lower_bound function, value = 3:
      [first, iter] = 0 0 0 1 1 1 1 2 2 2 2
      [iter, last] = 3 3 3 4 4 4 5 5 5
    upper_bound function, value = 3:
      [first, iter] = 0 0 0 1 1 1 1 2 2 2 2 3 3 3
      [iter, last] = 4 4 4 5 5 5
    euqual_range function value = 3:
     [vecpair->first, vecpair->second] = 3 3 3
    binary_search function value = 3:
    3 is  in array
    binary_search function value = 6:
    6 is not  in array

  • 相关函数有:

    std::includes std::set_difference
    std::set_intersection std::set_union
    std::set_symmetric_difference  
        
        
    1. #include <iostream>
    2. #include <vector>
    3. #include <algorithm>
    4. #include <functional>
    5. #include <string>
    6.  
    7. #define INIT_VECTOR(type, name, ...) \
    8. static const type name##_a[] = __VA_ARGS__; \
    9. vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
    10.  
    11. using namespace std;
    12. const int BIG_VECTOR_SIZE = 30;
    13.  
    14.  
    15. int main(int argc, char **argv)
    16. {
    17. using std::cout;
    18. using std::endl;
    19. INIT_VECTOR(int,foo1,{1,2,3,4,5,6,7,8,9,10,11,12});
    20. INIT_VECTOR(int,foo2,{2,4,6,8,10});
    21. INIT_VECTOR(int,foo3,{4,5,6,11,15});
    22. std::ostream_iterator<int>output(cout," ");
    23. cout<<"al contain:";
    24. std::copy(foo1.begin(),foo1.end(),output);
    25. cout<<"\na2 contain:";
    26. std::copy(foo2.begin(),foo2.end(),output);
    27. cout<<"\na3 contain:";
    28. std::copy(foo3.begin(),foo3.end(),output);
    29.  
    30. if(std::includes(foo1.begin(),foo1.end(),foo2.begin(),foo2.end()))
    31. cout<<"\nVal include v2:";
    32. else
    33. cout<<"\nVal does not include v2";
    34. if(std::includes(foo1.begin(),foo1.end(),foo3.begin(),foo3.end()))
    35. cout<<"\nVal include v3:";
    36. else
    37. cout<<"\nVal does not include v3.";
    38.  
    39. vector<int> difference;
    40. difference.resize(BIG_VECTOR_SIZE);
    41. vector<int>::iterator ptr=std::set_difference(foo1.begin(),foo1.end(),foo2.begin(),foo2.end(),difference.begin());
    42. cout<<"\nset_symmetric_difference of foo1 and foo2 is:";
    43. std::copy(difference.begin(),ptr,output);
    44.  
    45. vector<int> intersection;
    46. intersection.resize(BIG_VECTOR_SIZE);
    47. ptr=std::set_intersection(foo1.begin(),foo1.end(),foo2.begin(),foo2.end(),intersection.begin());
    48. cout<<"\nset_intersection of foo1 and foo2 is:";
    49. std::copy(intersection.begin(),ptr,output);
    50.  
    51. vector<int> symmetric_difference;
    52. symmetric_difference.resize(BIG_VECTOR_SIZE);
    53. ptr=std::set_symmetric_difference(foo1.begin(),foo1.end(),foo2.begin(),foo2.end(),symmetric_difference.begin());
    54. cout<<"\nset_symmetric_difference of foo1 and foo2 is:";
    55. std::copy(symmetric_difference.begin(),ptr,output);
    56.  
    57. vector<int> unionSet;
    58. unionSet.resize(BIG_VECTOR_SIZE);
    59. ptr=std::set_union(foo1.begin(),foo1.end(),foo3.begin(),foo3.end(),unionSet.begin());
    60. cout<<"\nset_union of foo1 and foo3 is:";
    61. std::copy(unionSet.begin(),ptr,output);
    62. cout<<endl;
    63. return 0;
    64. }

    输出

    foo1 contain:1 2 3 4 5 6 7 8 9 10 11 12
    foo2 contain:2 4 6 8 10
    foo3 contain:4 5 6 11 15
    foo1 include foo2:
    foo1 does not include v3.
    set_difference of foo1 and foo2 is:1 3 5 7 9 11 12
    set_intersection of foo1 and foo2 is:2 4 6 8 10
    set_symmetric_difference of foo1 and foo3 is:1 2 3 7 8 9 10 12 15
    set_union of foo1 and foo3 is:1 2 3 4 5 6 7 8 9 10 11 12 15

  • 相关函数有:

    std::make_heap std::push_heap
    std::pop_heap std::sort_heap
        
        
    1. #include<iostream>
    2. #include<algorithm>
    3. #include<vector>
    4. #include<functional>
    5.  
    6. namespace ClassFoo{
    7.  
    8. using namespace std;
    9. void PrintIntVector(vector<int>& foo) {
    10. vector <int>::iterator Iter1;
    11. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    12. cout << *Iter1 << " ";
    13. cout << endl;
    14. }
    15. void HeadOperation1(){
    16. int a[] = {1, 12, 15, 20, 30};
    17. vector<int> foo(a, a + sizeof(a) / sizeof(a[0]));
    18. PrintIntVector(foo);
    19. make_heap(foo.begin(), foo.end(), greater<int>());
    20. PrintIntVector(foo);
    21. pop_heap(foo.begin(), foo.end(), greater<int>());
    22. foo.pop_back();
    23. PrintIntVector(foo);
    24. foo.push_back(99);
    25. push_heap(foo.begin(), foo.end(), greater<int>());
    26. PrintIntVector(foo);
    27. sort_heap(foo.begin(), foo.end(), greater<int>());
    28. PrintIntVector(foo);
    29. }
    30.  
    31. }
    32. int main(int argc, char* argv[])
    33. {
    34. ClassFoo::HeadOperation1();
    35. return 0;
    36. }

    输出:

    1 12 15 20 30
    1 12 15 20 30
    12 20 15 30
    12 20 15 30 99
    99 30 20 15 12

  • 相关函数有:

    std::min_element std::max_element
        
        
    1. #include <iostream>
    2. #include <algorithm>
    3. #include <vector>
    4.  
    5. #define CLASSFOO_VECTOR(type, name, ...) \
    6. static const type name##_a[] = __VA_ARGS__; \
    7. std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
    8.  
    9. namespace ClassFoo{
    10.  
    11. using namespace std;
    12.  
    13. bool myfn(int i, int j) { return i<j; }
    14.  
    15. struct myclass {
    16. bool operator() (int i,int j) { return i<j; }
    17. } myobj;
    18.  
    19. void MinMaxElement() {
    20. CLASSFOO_VECTOR(int,foo,{3,7,2,5,6,4,9});
    21.  
    22. // 使用默认二元谓词函数
    23. cout << "最小的元素是:" << *min_element(foo.begin(),foo.end()) << endl;
    24. cout << "最大的元素是:" << *max_element(foo.begin(),foo.end()) << endl;
    25.  
    26. // 使用自定义二元谓词函数
    27. cout << "最小的元素是:" << *min_element(foo.begin(),foo.end(),myfn) << endl;
    28. cout << "最大的元素是:" << *max_element(foo.begin(),foo.end(),myfn) << endl;
    29.  
    30. // 使用自定义二元谓词函数对象
    31. cout << "最小的元素是:" << *min_element(foo.begin(),foo.end(),myobj) << endl;
    32. cout << "最大的元素是:" << *max_element(foo.begin(),foo.end(),myobj) << endl;
    33. }
    34.  
    35. }
    36. int main () {
    37. ClassFoo::MinMaxElement();
    38. return 0;
    39. }

    输出

    最小的元素是:2
    最大的元素是:9
    最小的元素是:2
    最大的元素是:9
    最小的元素是:2
    最大的元素是:9

  • 相关函数有:

    std::lexicographical_compare
        
        
    1. #include <iostream>
    2. #include <algorithm>
    3. #include <vector>
    4. #include <string>
    5.  
    6. namespace ClassFoo {
    7.  
    8. using namespace std;
    9. void LexicographicalCompare1() {
    10. string s("helio");
    11. string s2("hello");
    12.  
    13. vector<char> foo1(s.begin(), s.end());
    14. vector<char> foo2(s2.begin(), s2.end());
    15.  
    16. // Show that foo1 is lexicographically less than foo2:
    17. bool result = lexicographical_compare(
    18. foo1.begin(),
    19. foo1.end(),
    20. foo2.begin(),
    21. foo2.end());
    22. cout << "按字典序," << s << " < " << s2 << ":" ;
    23. cout << std::boolalpha << result << std::endl;
    24. }
    25. }
    26.  
    27. int main()
    28. {
    29. ClassFoo::LexicographicalCompare1();
    30. return 0;
    31. }

    输出

    按字典序,helio < hello:true

  • 相关函数有:

    std::next_permutation std::prev_permutation
        
        
    1. #include <iostream>
    2. #include <vector>
    3. #include <algorithm>
    4.  
    5. #define CLASSFOO_VECTOR(type, name, ...) \
    6. static const type name##_a[] = __VA_ARGS__; \
    7. std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
    8.  
    9. namespace ClassFoo{
    10. void PrintIntVector(std::vector<int>& foo) {
    11. std::vector <int>::iterator Iter1;
    12. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    13. std::cout << *Iter1 << " ";
    14. std::cout << std::endl;
    15. }
    16. void NextPermutation() {
    17. CLASSFOO_VECTOR(int,foo,{2,3,7});
    18. std::cout << "排列开始前:";
    19. PrintIntVector(foo);
    20. while ( std::next_permutation(foo.begin(),foo.end())) {
    21. PrintIntVector(foo);
    22. }
    23. std::cout << "排列结束后:";
    24. PrintIntVector(foo);
    25. }
    26. }
    27.  
    28. int main() {
    29. ClassFoo::NextPermutation();
    30. }

    输出

    排列开始前:2 3 7
    2 7 3
    3 2 7
    3 7 2
    7 2 3
    7 3 2
    排列结束后:2 3 7

  • 相关函数有:

    std::nth_element
        
        
    1. #include <iostream>
    2. #include <vector>
    3. #include <algorithm>
    4. #include <functional>
    5.  
    6. #define CLASSFOO_VECTOR(type, name, ...) \
    7. static const type name##_a[] = __VA_ARGS__; \
    8. std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
    9.  
    10. namespace ClassFoo{
    11. void PrintIntVector(std::vector<int>& foo) {
    12. std::vector <int>::iterator Iter1;
    13. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    14. std::cout << *Iter1 << " ";
    15. std::cout << std::endl;
    16. }
    17. void NthElement(){
    18. CLASSFOO_VECTOR(int,foo,{5, 6, 4, 3, 2, 6, 7, 9, 3});
    19. std::cout << "调用nth_element前:";
    20. PrintIntVector(foo);
    21. std::nth_element(foo.begin(), foo.begin() + foo.size()/2, foo.end());
    22. std::cout << "第一次调用nth_element后:";
    23. PrintIntVector(foo);
    24. std::cout << "中间元素是: " << foo[foo.size()/2] << '\n';
    25.  
    26. std::nth_element(foo.begin(), foo.begin()+1, foo.end(), std::greater<int>());
    27. std::cout << "第二次调用nth_element后:";
    28. PrintIntVector(foo);
    29. std::cout << "第二大元素是: " << foo[1] << '\n';
    30. }
    31. }
    32. int main()
    33. {
    34. ClassFoo::NthElement();
    35. return 0;
    36. }

    输出

    调用nth_element前:5 6 4 3 2 6 7 9 3
    第一次调用nth_element后:2 3 3 4 5 6 6 7 9
    中间元素是: 5
    第二次调用nth_element后:9 7 6 6 5 4 3 3 2
    第二大元素是: 7​

  • 所有满足(All of) C++11

    std::all_of
        
        
    1. // 返回是否所有数字都是偶数的
    2. std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; })

    任意满足(Any of) C++11

    std::any_of
        
        
    1. // 返回是否“在当前范围中,存在一元素,能被7整除"
    2. struct DivisibleBy
    3. {
    4. const int d;
    5. DivisibleBy(int n) : d(n) {}
    6. bool operator()(int n) const { return n % d == 0; }
    7. };
    8. if (std::any_of(v.cbegin(), v.cend(), DivisibleBy(7))) {
    9. std::cout << "At least one number is divisible by 7\n";
    10. }

    无一满足(None of) C++11

    std::none_of
        
        
    1. // 返回是否“在当前范围中,无负元素"
    2. std::none_of(foo.begin(), foo.end(), [](int i){return i<0;})

    对每一个(For each)

    std::for_each
        
        
    1. // 打印每个元素
    2. void myfunction (int i) { // function:
    3. std::cout << ' ' << i;
    4. }
    5. std::for_each (myvector.begin(), myvector.end(), myfunction);
        
        
    1. // 使用函数对象,打印每个元素
    2. struct myclass { // function object type:
    3. void operator() (int i) {std::cout << ' ' << i;}
    4. } myobject;
    5. std::for_each (foo.begin(), foo.end(), myobject);

    C++11

        
        
    1. // 使用lambda表达式使每个元素加1
    2. std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });

    拷贝(Copy)

    std::copy
        
        
    1. int myints[]={10,20,30,40,50,60,70};
    2. std::vector<int> myvector (7);
    3. std::copy ( myints, myints+7, myvector.begin() );
        
        
    1. // 将流输入迭代器中的内容发送到流输出迭代器
    2. copy (istream_iterator<string>(cin), // beginning of source
    3. istream_iterator<string>(), // end of source
    4. ostream_iterator<string>(cout,"\n")); // destination
        
        
    1. // 非常常用的序列输出
    2. #include <iostream>
    3. #include <vector>
    4. #include <string>
    5.  
    6. #define CLASSFOO_VECTOR(type, name, ...) \
    7. static const type name##_a[] = __VA_ARGS__; \
    8. std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
    9.  
    10. int main()
    11. {
    12. CLASSFOO_VECTOR(int,foo,{2,3,8,9,4,15});
    13. std::copy(foo.begin(),foo.end(),std::ostream_iterator<int>(std::cout, " "));
    14. }
    std::copy_if C++11
        
        
    1. std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
    std::copy_n C++11
        
        
    1. #include <iostream>
    2. #include <string>
    3. #include <algorithm>
    4. #include <iterator>
    5. int main()
    6. {
    7. std::string in = "1234567890";
    8. std::string out;
    9. std::copy_n(in.begin(), 4, std::back_inserter(out));
    10. std::cout << out << '\n';
    11. }
    std::copy_backward
        
        
    1. #include <iostream>
    2. #include <algorithm>
    3. #include <vector>
    4.  
    5. int main()
    6. {
    7. std::vector<int> foo_from;
    8. for (int i = 0; i < 10; i++) {
    9. foo_from.push_back(i);
    10. }
    11. std::vector<int> foo_to(15);
    12. std::copy_backward(foo_from.begin(), foo_from.end(), foo_to.end());
    13. std::cout << "foo_to contains: ";
    14. for (unsigned int i = 0; i < foo_to.size(); i++) {
    15. std::cout << foo_to[i] << " ";
    16. }
    17. std::cout << std::endl;
    18. return 0;
    19. }

    输出

    foo_to contains: 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9

    移动(Move) C++11

    std::move
        
        
    1. // 将foo的前四个元素移动到bar的开始位置
    2. std::move(foo.begin(), foo.begin()+4, bar.begin());
    std::move_backward
        
        
    1. // 将foo中所无元素移动bar中末尾前的元素中,“从后到前”移动
    2. std::move_backward(foo.begin(), foo.end(), bar.end());

    交换(Swap)

    std::swap_ranges
        
        
    1. // 交换两个范围的内容
    2. std::swap_ranges(foo.begin(), foo.begin()+3, bar.begin());
    std::iter_swap
        
        
    1. // 交换两个迭代器指向的元素
    2. std::iter_swap(foo+3,bar.begin()+2);

    改变(Transform)

    std::transform
        
        
    1. // 将foo中的每个元素加1,结果保存在bar中
    2. int op_increase (int i) { return ++i; }
    3. std::transform (foo.begin(), foo.end(), bar.begin(), op_increase);
        
        
    1. // 将foo与bar中的对应元素相加,结果保存在foo中
    2. std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());

    替换(Replace)

    std::replace
        
        
    1. // 将foo中值为20的元素以99赋值
    2. std::replace (foo.begin(), foo.end(), 20, 99);
    std::replace_if
        
        
    1. // 将向量中所有奇数赋值为0
    2. bool IsOdd (int i) { return ((i%2)==1); }
    3. std::replace_if (foo.begin(), foo.end(), IsOdd, 0);
    std::replace_copy
        
        
    1. // 拷贝时替换
    2. std::replace_copy (foo, foo+8, bar.begin(), 20, 99);
    std::replace_copy_if
        
        
    1. // 拷贝时满足条件就替换
    2. bool IsOdd (int i) { return ((i%2)==1); }
    3. std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0);

    填充(Fill)

    std::fill
        
        
    1. // 用值填充某个范围
    2. std::fill (foo.begin(),foo.begin()+4,5);
    std::fill_n
        
        
    1. // 用值填充某个位置开始的指定个数的元素
    2. std::fill_n (myvector.begin(),4,20);

    产生(Generate)序列

    std::generate
        
        
    1. #include <iostream> // std::cout
    2. #include <algorithm> // std::generate
    3. #include <vector> // std::vector
    4. #include <ctime> // std::time
    5. #include <cstdlib> // std::rand, std::srand
    6.  
    7. namespace ClassFoo{
    8. // 生成器函数:
    9. int RandomNumber () { return (std::rand()%100); }
    10.  
    11. // 生成器对象:
    12. struct c_unique {
    13. int current;
    14. c_unique() {current=0;}
    15. int operator()() {return ++current;}
    16. } UniqueNumber;
    17.  
    18. void PrintIntVector(std::vector<int>& foo) {
    19. std::vector <int>::iterator Iter1;
    20. for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
    21. std::cout << *Iter1 << " ";
    22. std::cout << std::endl;
    23. }
    24.  
    25. void GenerateVector() {
    26. std::srand ( unsigned ( std::time(0) ) );
    27.  
    28. std::vector<int> foo (8);
    29.  
    30. // 用随机数赋值序列
    31. std::generate (foo.begin(), foo.end(), RandomNumber);
    32. PrintIntVector(foo);
    33. // 用唯一值赋值序列
    34. std::generate (foo.begin(), foo.end(), UniqueNumber);
    35. PrintIntVector(foo);
    36. }
    37. }
    38. int main () {
    39. ClassFoo::GenerateVector();
    40. return 0;
    41. }

    输出

    11 38 49 23 63 65 60 62
    1 2 3 4 5 6 7 8

    std::generate_n
        
        
    1. std::generate_n(foo.begin(), 4, std::rand);

    移除(Remove)

    std::remove
        
        
    1. // 删除值为3的元素
    2. foo.erase(std::remove(foo.begin(), foo.end(), 3),foo.end());
    std::remove_if
        
        
    1. // 删除容器中满足指定条件的元素
    2. bool IsOdd (int& i) { return ((i % 2)==1); }
    3. foo.erase(std::remove_if(foo.begin(), foo.end(), IsOdd),foo.end());

    使唯一(Unique)

    std::unique
        
        
    1. // 移除连续相等的部分元素,留下一个
    2. std::unique(v.begin(), v.end());
    std::unique_copy
        
        
    1. // 打印删除连续元素后的剩余元素
    2. unique_copy(coll.begin(), coll.end(), // source
    3. ostream_iterator<int>(cout," ")); // destination

    反转(Reverse)

    std::reverse
        
        
    1. // 反转序列
    2. std::reverse(foo.begin(), foo.end());
    std::reverse_copy
        
        
    1. // 将foo的反转序列拷贝到bar
    2. std::reverse_copy(std::begin(foo), std::end(foo), std::begin(bar));

    循环(Rotate)

    std::rotate
        
        
    1. // 循环使位置3处的元素成为第一个元素
    2. std::rotate(foo.begin(),foo.begin()+3,foo.end());
    std::rotate_copy
        
        
    1. // 循环使位置3处的元素成为第一个元素,将循环的结果保存到bar中
    2. std::rotate(foo.begin(),foo.begin()+3,foo.end(),bar.begin());

    随机移动(Random shuffle)

    std::random_shuffle
        
        
    1. // 使用内置的随机数生成器随机移动元素
    2. std::random_shuffle ( foo.begin(), foo.end() );
        
        
    1. // 使用自定义的随机数生成器随机移动元素
    2. int myrandom (int i) { return std::rand()%i;}
    3. std::random_shuffle ( foo.begin(), foo.end(), myrandom);
    std::shuffle C++11
        
        
    1. // 使用在<random>中定义的标准随机数生成器
    2. shuffle (foo.begin(), foo.end(), std::default_random_engine(seed));

    划分(Partitions)

    std::partition
        
        
    1. #include <iostream> // std::cout
    2. #include <algorithm> // std::partition
    3. #include <vector> // std::vector
    4.  
    5. namespace ClassFoo{
    6. bool IsOdd (int i) { return (i%2)==1; }
    7. void Partition() {
    8. std::vector<int> foo;
    9.  
    10. for (int i=1; i<10; ++i) foo.push_back(i); // 1 2 3 4 5 6 7 8 9
    11.  
    12. std::vector<int>::iterator bound;
    13. bound = std::partition (foo.begin(), foo.end(), IsOdd);
    14.  
    15. std::cout << "odd elements:";
    16. for (std::vector<int>::iterator it=foo.begin(); it!=bound; ++it)
    17. std::cout << ' ' << *it;
    18. std::cout << '\n';
    19.  
    20. std::cout << "even elements:";
    21. for (std::vector<int>::iterator it=bound; it!=foo.end(); ++it)
    22. std::cout << ' ' << *it;
    23. std::cout << '\n';
    24. }
    25. }
    26.  
    27. int main () {
    28. ClassFoo::Partition();
    29. return 0;
    30. }

    输出

    odd elements: 1 9 3 7 5
    even elements: 6 4 8 2

    std::is_partitioned C++11
        
        
    1. #include <iostream> // std::cout
    2. #include <algorithm> // std::is_partitioned
    3. #include <array> // std::array
    4.  
    5. namespace ClassFoo{
    6. bool IsOdd (int i) { return (i % 2)==1; }
    7. void IsPartitioned() {
    8. std::array<int,7> foo {1,2,3,4,5,6,7};
    9.  
    10. // 打印内容
    11. std::cout << "foo:"; for (int& x:foo) std::cout << ' ' << x;
    12. if ( std::is_partitioned(foo.begin(),foo.end(),IsOdd) )
    13. std::cout << " (partitioned)\n";
    14. else
    15. std::cout << " (not partitioned)\n";
    16.  
    17. // 划分区块:
    18. std::partition (foo.begin(),foo.end(),IsOdd);
    19.  
    20. // 再次打印内容
    21. std::cout << "foo:"; for (int& x:foo) std::cout << ' ' << x;
    22. if ( std::is_partitioned(foo.begin(),foo.end(),IsOdd) )
    23. std::cout << " (partitioned)\n";
    24. else
    25. std::cout << " (not partitioned)\n";
    26. }
    27. }
    28. int main () {
    29. ClassFoo::IsPartitioned();
    30. return 0;
    31. }

    输出

    foo: 1 2 3 4 5 6 7 (not partitioned)
    foo: 1 7 3 5 4 6 2 (partitioned)

    std::stable_partition
        
        
    1. bool IsOdd (int i) { return (i%2)==1; }
    2. std::stable_partition (foo.begin(), foo.end(), IsOdd);
    std::partition_copy C++11
        
        
    1. bool IsOdd (int i) { return (i%2)==1; }
    2. std::partition_copy (foo.begin(), foo.end(), odd.begin(), even.begin(), IsOdd);
    std::partition_point C++11
        
        
    1. // 返回划分临界点
    2. std::partition_point(foo.begin(),foo.end(),IsOdd);

    合并(Merge)

    std::merge
        
        
    1. // 合并两个范围的内容到一个容器中
    2. std::merge (foo1,foo1+5,foo2,foo2+5,foo3.begin());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值