<algorithm> 头文件中包含大量与 vector
相关的算法,这些算法同样适用于其它容器,比如 std::list
等。
http://classfoo.com/ccby/article/cIBahI
-
相关函数有:
std::sort
std::partial_sort
std::stable_sort
普通排序
Example 1
- #include <vector>
- #include <algorithm>
- #include <functional> // For greater<int>()
- #include <iostream>
- namespace ClassFoo{
- // 返回第一个元素是否比第二个元素大
- bool UDgreater ( int elem1, int elem2 )
- {
- return elem1 > elem2;
- }
- void NormalSort1() {
- using namespace std;
- vector <int> foo;
- vector <int>::iterator Iter1;
- int i;
- for ( i = 0 ; i <= 5 ; i++ )
- {
- foo.push_back( 2 * i );
- }
- int ii;
- for ( ii = 0 ; ii <= 5 ; ii++ )
- {
- foo.push_back( 2 * ii + 1 );
- }
- cout << "Original vector foo = ( " ;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // 按升序排序,使用默认的二元谓词函数
- sort( foo.begin( ), foo.end( ) );
- cout << "Sorted vector foo = ( " ;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // 按降序排序,提供二元谓词函数
- sort( foo.begin( ), foo.end( ), greater<int>( ) );
- cout << "Resorted (greater) vector foo = ( " ;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- // 使用自定义的二元谓词函数
- sort( foo.begin( ), foo.end( ), UDgreater );
- cout << "Resorted (UDgreater) vector foo = ( " ;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")" << endl;
- }
- }
- int main()
- {
- ClassFoo::NormalSort1();
- return 0;
- }
输出:
Example 2
使用函数对象。
- #include <vector>
- #include <algorithm>// for generate、partial_sort
- #include <functional>
- #include <iostream>
- #include <cstdlib> // std::rand, std::srand
- #include <ctime> // std::time
- namespace ClassFoo{
- struct {
- bool operator()(int a, int b)
- {
- return a < b;
- }
- } FooLess;
- void PrintIntVector(std::vector<int>& foo) {
- std::vector <int>::iterator Iter1;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- std::cout << *Iter1 << " ";
- std::cout << std::endl;
- }
- void NormalSort2() {
- using namespace std;
- vector<int> foo;
- int i;
- for ( i = 0 ; i <= 5 ; i++ )
- {
- foo.push_back( 2 * i );
- }
- int ii;
- for ( ii = 0 ; ii <= 5 ; ii++ )
- {
- foo.push_back( 2 * ii + 1 );
- }
- PrintIntVector(foo);
- std::sort(foo.begin(), foo.end(), FooLess);
- PrintIntVector(foo);
- }
- }
- int main(void)
- {
- ClassFoo::NormalSort2();
- return 0;
- }
输出:
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 表达式。
- #include <vector>
- #include <algorithm> // for generate、partial_sort
- #include <functional>
- #include <iostream>
- #include <cstdlib> // std::rand, std::srand
- #include <ctime> // std::time
- namespace ClassFoo{
- void PrintIntVector(std::vector<int>& foo) {
- std::vector <int>::iterator Iter1;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- std::cout << *Iter1 << " ";
- std::cout << std::endl;
- }
- void NormalSort3() {
- using namespace std;
- vector<int> foo;
- int i;
- for ( i = 0 ; i <= 5 ; i++ )
- {
- foo.push_back( 2 * i );
- }
- int ii;
- for ( ii = 0 ; ii <= 5 ; ii++ )
- {
- foo.push_back( 2 * ii + 1 );
- }
- PrintIntVector(foo);
- std::sort(foo.begin(), foo.end(), [](int a, int b) {
- return b < a;
- });
- PrintIntVector(foo);
- }
- }
- int main(void)
- {
- ClassFoo::NormalSort3();
- return 0;
- }
输出:
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)
- #include <vector>
- #include <algorithm> // for generate、partial_sort
- #include <functional>
- #include <iostream>
- #include <cstdlib> // std::rand, std::srand
- #include <ctime> // std::time
- namespace ClassFoo{
- int RandomNumber () { return (std::rand()%100); }
- void PartialSort1()
- {
- std::srand ( unsigned ( std::time(0) ) );
- std::vector<int> foo(15);
- std::generate(foo.begin(), foo.end(), RandomNumber);
- // 部份排序前七个元素
- std::partial_sort(foo.begin(), foo.begin() + 7, foo.end());
- }
- }
- int main(void)
- {
- ClassFoo::PartialSort1();
- return 0;
- }
稳定排序
Example 1
- #include <vector>
- #include <algorithm>
- #include <functional> // For greater<int>( )
- #include <iostream>
- namespace ClassFoo{
- // 返回第一个元素是否比第二个元素大
- bool UDgreater(int elem1, int elem2 )
- {
- return elem1 > elem2;
- }
- void StableSort1() {
- using namespace std;
- vector <int> v1;
- vector <int>::iterator Iter1;
- int i;
- for ( i = 0 ; i <= 5 ; i++ )
- {
- v1.push_back( 2 * i );
- }
- for ( i = 0 ; i <= 5 ; i++ )
- {
- v1.push_back( 2 * i );
- }
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << endl;
- // 按升序排序,使用默认的二元谓词函数
- stable_sort(v1.begin( ), v1.end( ) );
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << endl;
- // 按降序排序,提供二元谓词函数
- stable_sort(v1.begin( ), v1.end( ), greater<int>( ) );
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << endl;
- // 按降序排序,使用自定义的二元谓词函数
- stable_sort(v1.begin( ), v1.end( ), UDgreater );
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << endl;
- }
- }
- int main( )
- {
- ClassFoo::StableSort1();
- return 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
- #include <iostream>
- #include <algorithm>
- #include <functional>
- #include <vector>
- // 用在此处是为了方便简洁, 在实际编程中慎用
- using namespace std;
- void main()
- {
- int iarray[]={0,1,2,3,4,5,6,6,6,7,8};
- vector<int> foo1(iarray,iarray+sizeof(iarray)/sizeof(int));
- int iarray1[]={6,6};
- vector<int> foo2(iarray1,iarray1+sizeof(iarray1)/sizeof(int));
- int iarray2[]={5,6};
- vector<int> foo3(iarray2,iarray2+sizeof(iarray2)/sizeof(int));
- int iarray3[]={0,1,2,3,4,5,7,7,7,9,7};
- vector<int> foo4(iarray3,iarray3+sizeof(iarray3)/sizeof(int));
- //找出foo1之中相邻元素值相等的第一个元素
- cout<<*adjacent_find(foo1.begin(),foo1.end())<<endl;
- //找出foo1之中元素值为6的元素个数
- cout<<count(foo1.begin(),foo1.end(),6)<<endl;
- //找出foo1之中小于7的元素个数
- cout<<count_if(foo1.begin(),foo1.end(),bind2nd(less<int>(),7))<<endl;
- //找出foo1之中元素值为4的第一个元素所在位置的元素
- cout<<*find(foo1.begin(),foo1.end(),4)<<endl;
- //找出foo1之中大于2的第一个元素所在位置的元素
- cout<<*find_if(foo1.begin(),foo1.end(),bind2nd(greater<int>(),2))
- <<endl;
- //找出foo1之中子序列foo2所出现的最后一个位置,再往后3个位置的元素
- cout<<*(find_end(foo1.begin(),foo1.end(),foo2.begin(),
- foo2.end())+3)<<endl;
- //找出foo1之中子序列foo2所出现的第一个位置,再往后3个位置的元素
- cout<<*(find_first_of(foo1.begin(),foo1.end(),foo2.begin(),
- foo2.end())+3)<<endl;
- //子序列foo3在foo1中出现的起点位置元素
- cout<<*search(foo1.begin(),foo1.end(),foo3.begin(),foo3.end())
- <<endl;
- //查找连续出现3个6的起点位置元素
- cout<<*search_n(foo1.begin(),foo1.end(),3,6,equal_to<int>())<<endl;
- //判断两个区间foo1和foo4相等否(0为假,1为真)
- cout << equal(foo1.begin(), foo1.end(), foo4.begin()) << endl;
- //查找区间foo4在foo1中不匹配点的位置
- pair<std::vector<int>::iterator,std::vector<int>::iterator>result=
- mismatch(foo1.begin(),foo1.end(),foo4.begin());
- cout<< result.first - foo1.begin() << endl;
- }
输出:
-
- ClassFoo 编辑于 07-28
相关函数有:
std::lower_bound
std::upper_bound
std::equal_range
std::binary_search
Example 1
- #include <vector>
- #include <algorithm> // for lower_bound()、greater<int>()
- #include <functional>
- #include <iostream>
- // 用在此处是为了方便简洁, 在实际编程中慎用
- using namespace std;
- // 返回elem1的绝对值是否比elem2的绝对值小
- bool mod_lesser(int elem1, int elem2)
- {
- if(elem1 < 0)
- elem1 = - elem1;
- if(elem2 < 0)
- elem2 = - elem2;
- return (elem1 < elem2);
- }
- int main(void)
- {
- vector <int> foo1;
- vector <int>::iterator Iter1, Result1;
- int i, j;
- // 插入数据
- for(i = -3; i <= 6; i++)
- foo1.push_back(i);
- for(j =-5; j <= 2; j++)
- foo1.push_back(j);
- cout<<"操作: sort(foo1.begin(), foo1.end())"<< endl;
- sort(foo1.begin(), foo1.end());
- cout<<"使用默认的二元谓词“是否小于”排序后的结果:";
- for(Iter1 = foo1.begin(); Iter1 != foo1.end(); Iter1++)
- cout<<*Iter1<<" ";
- cout<<endl;
- vector <int> foo2(foo1);
- vector <int>::iterator Iter2, Result2;
- cout<<"操作: sort(foo2.begin(), foo2.end(), greater<int>())"<<endl;
- sort(foo2.begin(), foo2.end(), greater<int>());
- cout<<"使用二元谓词“是否大于”排序后的结果:";
- for(Iter2 = foo2.begin(); Iter2 != foo2.end(); Iter2++)
- cout<<*Iter2<<" ";
- cout<<endl;
- vector <int> foo3(foo1);
- vector <int>::iterator Iter3, Result3;
- cout<<"操作: sort(foo3.begin(), foo3.end(), mod_lesser)"<<endl;
- sort(foo3.begin(), foo3.end(), mod_lesser);
- cout<<"使用二元谓词 mod_lesser 排序后的结果:";
- for(Iter3 = foo3.begin(); Iter3 != foo3.end(); Iter3++)
- cout<<*Iter3<<" ";
- cout<<endl;
- cout<<"操作: lower_bound(foo1.begin(), foo1.end(), 5)"<<endl;
- // 使用默认的二元谓词“是否小于”二分查找值为5的元素的位置
- Result1 = lower_bound(foo1.begin(), foo1.end(), 5);
- cout<<"在foo1中二分查找值为5的元素的位置对应的值(即5):"<<*Result1<<endl;
- Result2 = lower_bound(foo2.begin(), foo2.end(), 5, greater<int>());
- // 使用二元谓词函数 greater<int>() 二分查找值为5的元素的位置
- cout<<"在foo1中二分查找值为5的元素的位置对应的值(即5):"<<*Result2<<endl;
- cout<<"操作: lower_bound(foo3.begin(), foo3.end(), 5, mod_lesser)"<<endl;
- // 使用二元谓词函数 mod_lesser 二分查找值为5的元素的位置
- Result3 = lower_bound(foo3.begin(), foo3.end(), 5, mod_lesser);
- cout<<"在foo1中二分查找值为5的元素的位置对应的值(即5或-5):"<<*Result3<<endl;
- return 0;
- }
输出:
Example 2
- #include <algorithm>
- #include <iostream>
- #include <iterator>
- #include <vector>
- // 用在此处是为了方便简洁, 在实际编程中慎用
- using namespace std;
- int main()
- {
- vector<int> v;
- vector<int>::iterator iter;
- pair<vector<int>::iterator, vector<int>::iterator> vecpair;
- for(int i = 1; i<= 20; i++) {
- v.push_back(i%6);
- }
- sort(v.begin(), v.end());
- //将各个元素拷贝到输出流迭代器中
- copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
- cout << endl;
- /* lower_bound */
- cout << "lower_bound function, value = 3: " << endl;
- iter = lower_bound(v.begin(), v.end(), 3);
- cout << " [first, iter] = ";
- copy(v.begin(), iter, ostream_iterator<int>(cout, " "));
- cout << endl;
- cout << " [iter, last] = ";
- copy(iter, v.end(), ostream_iterator<int>(cout, " "));
- cout << endl;
- /* upper_bound */
- cout << "upper_bound function, value = 3: " << endl;
- iter = upper_bound(v.begin(), v.end(), 3);
- cout << " [first, iter] = ";
- copy(v.begin(), iter, ostream_iterator<int>(cout, " "));
- cout << endl;
- cout << " [iter, last] = ";
- copy(iter, v.end(), ostream_iterator<int>(cout, " "));
- cout << endl;
- /* equal_range */
- cout << "euqual_range function value = 3: " << endl;
- vecpair = equal_range(v.begin(), v.end(), 3);
- cout << " [vecpair->first, vecpair->second] = ";
- copy(vecpair.first, vecpair.second, ostream_iterator<int>(cout, " "));
- cout << endl;
- /* binary_search */
- cout << "binary_search function value = 3: " << endl;
- cout << "3 is " << (binary_search(v.begin(), v.end(), 3) ? "": "not ") << " in array" << endl;
- /* binary_search */
- cout << "binary_search function value = 6: " << endl;
- cout << "6 is " << (binary_search(v.begin(), v.end(), 6) ? "": "not ") << " in array" << endl;
- }
输出:
-
相关函数有:
std::includes
std::set_difference
std::set_intersection
std::set_union
std::set_symmetric_difference
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <functional>
- #include <string>
- #define INIT_VECTOR(type, name, ...) \
- static const type name##_a[] = __VA_ARGS__; \
- vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
- using namespace std;
- const int BIG_VECTOR_SIZE = 30;
- int main(int argc, char **argv)
- {
- using std::cout;
- using std::endl;
- INIT_VECTOR(int,foo1,{1,2,3,4,5,6,7,8,9,10,11,12});
- INIT_VECTOR(int,foo2,{2,4,6,8,10});
- INIT_VECTOR(int,foo3,{4,5,6,11,15});
- std::ostream_iterator<int>output(cout," ");
- cout<<"al contain:";
- std::copy(foo1.begin(),foo1.end(),output);
- cout<<"\na2 contain:";
- std::copy(foo2.begin(),foo2.end(),output);
- cout<<"\na3 contain:";
- std::copy(foo3.begin(),foo3.end(),output);
- if(std::includes(foo1.begin(),foo1.end(),foo2.begin(),foo2.end()))
- cout<<"\nVal include v2:";
- else
- cout<<"\nVal does not include v2";
- if(std::includes(foo1.begin(),foo1.end(),foo3.begin(),foo3.end()))
- cout<<"\nVal include v3:";
- else
- cout<<"\nVal does not include v3.";
- vector<int> difference;
- difference.resize(BIG_VECTOR_SIZE);
- vector<int>::iterator ptr=std::set_difference(foo1.begin(),foo1.end(),foo2.begin(),foo2.end(),difference.begin());
- cout<<"\nset_symmetric_difference of foo1 and foo2 is:";
- std::copy(difference.begin(),ptr,output);
- vector<int> intersection;
- intersection.resize(BIG_VECTOR_SIZE);
- ptr=std::set_intersection(foo1.begin(),foo1.end(),foo2.begin(),foo2.end(),intersection.begin());
- cout<<"\nset_intersection of foo1 and foo2 is:";
- std::copy(intersection.begin(),ptr,output);
- vector<int> symmetric_difference;
- symmetric_difference.resize(BIG_VECTOR_SIZE);
- ptr=std::set_symmetric_difference(foo1.begin(),foo1.end(),foo2.begin(),foo2.end(),symmetric_difference.begin());
- cout<<"\nset_symmetric_difference of foo1 and foo2 is:";
- std::copy(symmetric_difference.begin(),ptr,output);
- vector<int> unionSet;
- unionSet.resize(BIG_VECTOR_SIZE);
- ptr=std::set_union(foo1.begin(),foo1.end(),foo3.begin(),foo3.end(),unionSet.begin());
- cout<<"\nset_union of foo1 and foo3 is:";
- std::copy(unionSet.begin(),ptr,output);
- cout<<endl;
- return 0;
- }
输出:
-
相关函数有:
std::make_heap
std::push_heap
std::pop_heap
std::sort_heap
- #include<iostream>
- #include<algorithm>
- #include<vector>
- #include<functional>
- namespace ClassFoo{
- using namespace std;
- void PrintIntVector(vector<int>& foo) {
- vector <int>::iterator Iter1;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << endl;
- }
- void HeadOperation1(){
- int a[] = {1, 12, 15, 20, 30};
- vector<int> foo(a, a + sizeof(a) / sizeof(a[0]));
- PrintIntVector(foo);
- make_heap(foo.begin(), foo.end(), greater<int>());
- PrintIntVector(foo);
- pop_heap(foo.begin(), foo.end(), greater<int>());
- foo.pop_back();
- PrintIntVector(foo);
- foo.push_back(99);
- push_heap(foo.begin(), foo.end(), greater<int>());
- PrintIntVector(foo);
- sort_heap(foo.begin(), foo.end(), greater<int>());
- PrintIntVector(foo);
- }
- }
- int main(int argc, char* argv[])
- {
- ClassFoo::HeadOperation1();
- return 0;
- }
输出:
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
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #define CLASSFOO_VECTOR(type, name, ...) \
- static const type name##_a[] = __VA_ARGS__; \
- std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
- namespace ClassFoo{
- using namespace std;
- bool myfn(int i, int j) { return i<j; }
- struct myclass {
- bool operator() (int i,int j) { return i<j; }
- } myobj;
- void MinMaxElement() {
- CLASSFOO_VECTOR(int,foo,{3,7,2,5,6,4,9});
- // 使用默认二元谓词函数
- cout << "最小的元素是:" << *min_element(foo.begin(),foo.end()) << endl;
- cout << "最大的元素是:" << *max_element(foo.begin(),foo.end()) << endl;
- // 使用自定义二元谓词函数
- cout << "最小的元素是:" << *min_element(foo.begin(),foo.end(),myfn) << endl;
- cout << "最大的元素是:" << *max_element(foo.begin(),foo.end(),myfn) << endl;
- // 使用自定义二元谓词函数对象
- cout << "最小的元素是:" << *min_element(foo.begin(),foo.end(),myobj) << endl;
- cout << "最大的元素是:" << *max_element(foo.begin(),foo.end(),myobj) << endl;
- }
- }
- int main () {
- ClassFoo::MinMaxElement();
- return 0;
- }
输出:
-
相关函数有:
std::lexicographical_compare
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <string>
- namespace ClassFoo {
- using namespace std;
- void LexicographicalCompare1() {
- string s("helio");
- string s2("hello");
- vector<char> foo1(s.begin(), s.end());
- vector<char> foo2(s2.begin(), s2.end());
- // Show that foo1 is lexicographically less than foo2:
- bool result = lexicographical_compare(
- foo1.begin(),
- foo1.end(),
- foo2.begin(),
- foo2.end());
- cout << "按字典序," << s << " < " << s2 << ":" ;
- cout << std::boolalpha << result << std::endl;
- }
- }
- int main()
- {
- ClassFoo::LexicographicalCompare1();
- return 0;
- }
输出:
-
相关函数有:
std::next_permutation
std::prev_permutation
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #define CLASSFOO_VECTOR(type, name, ...) \
- static const type name##_a[] = __VA_ARGS__; \
- std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
- namespace ClassFoo{
- void PrintIntVector(std::vector<int>& foo) {
- std::vector <int>::iterator Iter1;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- std::cout << *Iter1 << " ";
- std::cout << std::endl;
- }
- void NextPermutation() {
- CLASSFOO_VECTOR(int,foo,{2,3,7});
- std::cout << "排列开始前:";
- PrintIntVector(foo);
- while ( std::next_permutation(foo.begin(),foo.end())) {
- PrintIntVector(foo);
- }
- std::cout << "排列结束后:";
- PrintIntVector(foo);
- }
- }
- int main() {
- ClassFoo::NextPermutation();
- }
输出:
-
相关函数有:
std::nth_element
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <functional>
- #define CLASSFOO_VECTOR(type, name, ...) \
- static const type name##_a[] = __VA_ARGS__; \
- std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
- namespace ClassFoo{
- void PrintIntVector(std::vector<int>& foo) {
- std::vector <int>::iterator Iter1;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- std::cout << *Iter1 << " ";
- std::cout << std::endl;
- }
- void NthElement(){
- CLASSFOO_VECTOR(int,foo,{5, 6, 4, 3, 2, 6, 7, 9, 3});
- std::cout << "调用nth_element前:";
- PrintIntVector(foo);
- std::nth_element(foo.begin(), foo.begin() + foo.size()/2, foo.end());
- std::cout << "第一次调用nth_element后:";
- PrintIntVector(foo);
- std::cout << "中间元素是: " << foo[foo.size()/2] << '\n';
- std::nth_element(foo.begin(), foo.begin()+1, foo.end(), std::greater<int>());
- std::cout << "第二次调用nth_element后:";
- PrintIntVector(foo);
- std::cout << "第二大元素是: " << foo[1] << '\n';
- }
- }
- int main()
- {
- ClassFoo::NthElement();
- return 0;
- }
输出:
-
所有满足(All of) C++11
std::all_of
- // 返回是否所有数字都是偶数的
- std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; })
任意满足(Any of) C++11
std::any_of
- // 返回是否“在当前范围中,存在一元素,能被7整除"
- struct DivisibleBy
- {
- const int d;
- DivisibleBy(int n) : d(n) {}
- bool operator()(int n) const { return n % d == 0; }
- };
- if (std::any_of(v.cbegin(), v.cend(), DivisibleBy(7))) {
- std::cout << "At least one number is divisible by 7\n";
- }
无一满足(None of) C++11
std::none_of
- // 返回是否“在当前范围中,无负元素"
- std::none_of(foo.begin(), foo.end(), [](int i){return i<0;})
对每一个(For each)
std::for_each
- // 打印每个元素
- void myfunction (int i) { // function:
- std::cout << ' ' << i;
- }
- std::for_each (myvector.begin(), myvector.end(), myfunction);
- // 使用函数对象,打印每个元素
- struct myclass { // function object type:
- void operator() (int i) {std::cout << ' ' << i;}
- } myobject;
- std::for_each (foo.begin(), foo.end(), myobject);
C++11
- // 使用lambda表达式使每个元素加1
- std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });
拷贝(Copy)
std::copy
- int myints[]={10,20,30,40,50,60,70};
- std::vector<int> myvector (7);
- std::copy ( myints, myints+7, myvector.begin() );
- // 将流输入迭代器中的内容发送到流输出迭代器
- copy (istream_iterator<string>(cin), // beginning of source
- istream_iterator<string>(), // end of source
- ostream_iterator<string>(cout,"\n")); // destination
- // 非常常用的序列输出
- #include <iostream>
- #include <vector>
- #include <string>
- #define CLASSFOO_VECTOR(type, name, ...) \
- static const type name##_a[] = __VA_ARGS__; \
- std::vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
- int main()
- {
- CLASSFOO_VECTOR(int,foo,{2,3,8,9,4,15});
- std::copy(foo.begin(),foo.end(),std::ostream_iterator<int>(std::cout, " "));
- }
std::copy_if
C++11- std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
std::copy_n
C++11- #include <iostream>
- #include <string>
- #include <algorithm>
- #include <iterator>
- int main()
- {
- std::string in = "1234567890";
- std::string out;
- std::copy_n(in.begin(), 4, std::back_inserter(out));
- std::cout << out << '\n';
- }
std::copy_backward
- #include <iostream>
- #include <algorithm>
- #include <vector>
- int main()
- {
- std::vector<int> foo_from;
- for (int i = 0; i < 10; i++) {
- foo_from.push_back(i);
- }
- std::vector<int> foo_to(15);
- std::copy_backward(foo_from.begin(), foo_from.end(), foo_to.end());
- std::cout << "foo_to contains: ";
- for (unsigned int i = 0; i < foo_to.size(); i++) {
- std::cout << foo_to[i] << " ";
- }
- std::cout << std::endl;
- return 0;
- }
输出:
foo_to contains: 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9
移动(Move) C++11
std::move
- // 将foo的前四个元素移动到bar的开始位置
- std::move(foo.begin(), foo.begin()+4, bar.begin());
std::move_backward
- // 将foo中所无元素移动bar中末尾前的元素中,“从后到前”移动
- std::move_backward(foo.begin(), foo.end(), bar.end());
交换(Swap)
std::swap_ranges
- // 交换两个范围的内容
- std::swap_ranges(foo.begin(), foo.begin()+3, bar.begin());
std::iter_swap
- // 交换两个迭代器指向的元素
- std::iter_swap(foo+3,bar.begin()+2);
改变(Transform)
std::transform
- // 将foo中的每个元素加1,结果保存在bar中
- int op_increase (int i) { return ++i; }
- std::transform (foo.begin(), foo.end(), bar.begin(), op_increase);
- // 将foo与bar中的对应元素相加,结果保存在foo中
- std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());
替换(Replace)
std::replace
- // 将foo中值为20的元素以99赋值
- std::replace (foo.begin(), foo.end(), 20, 99);
std::replace_if
- // 将向量中所有奇数赋值为0
- bool IsOdd (int i) { return ((i%2)==1); }
- std::replace_if (foo.begin(), foo.end(), IsOdd, 0);
std::replace_copy
- // 拷贝时替换
- std::replace_copy (foo, foo+8, bar.begin(), 20, 99);
std::replace_copy_if
- // 拷贝时满足条件就替换
- bool IsOdd (int i) { return ((i%2)==1); }
- std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0);
填充(Fill)
std::fill
- // 用值填充某个范围
- std::fill (foo.begin(),foo.begin()+4,5);
std::fill_n
- // 用值填充某个位置开始的指定个数的元素
- std::fill_n (myvector.begin(),4,20);
产生(Generate)序列
std::generate
- #include <iostream> // std::cout
- #include <algorithm> // std::generate
- #include <vector> // std::vector
- #include <ctime> // std::time
- #include <cstdlib> // std::rand, std::srand
- namespace ClassFoo{
- // 生成器函数:
- int RandomNumber () { return (std::rand()%100); }
- // 生成器对象:
- struct c_unique {
- int current;
- c_unique() {current=0;}
- int operator()() {return ++current;}
- } UniqueNumber;
- void PrintIntVector(std::vector<int>& foo) {
- std::vector <int>::iterator Iter1;
- for ( Iter1 = foo.begin( ) ; Iter1 != foo.end( ) ; Iter1++ )
- std::cout << *Iter1 << " ";
- std::cout << std::endl;
- }
- void GenerateVector() {
- std::srand ( unsigned ( std::time(0) ) );
- std::vector<int> foo (8);
- // 用随机数赋值序列
- std::generate (foo.begin(), foo.end(), RandomNumber);
- PrintIntVector(foo);
- // 用唯一值赋值序列
- std::generate (foo.begin(), foo.end(), UniqueNumber);
- PrintIntVector(foo);
- }
- }
- int main () {
- ClassFoo::GenerateVector();
- return 0;
- }
输出:
11 38 49 23 63 65 60 62
1 2 3 4 5 6 7 8
std::generate_n
- std::generate_n(foo.begin(), 4, std::rand);
移除(Remove)
std::remove
- // 删除值为3的元素
- foo.erase(std::remove(foo.begin(), foo.end(), 3),foo.end());
std::remove_if
- // 删除容器中满足指定条件的元素
- bool IsOdd (int& i) { return ((i % 2)==1); }
- foo.erase(std::remove_if(foo.begin(), foo.end(), IsOdd),foo.end());
使唯一(Unique)
std::unique
- // 移除连续相等的部分元素,留下一个
- std::unique(v.begin(), v.end());
std::unique_copy
- // 打印删除连续元素后的剩余元素
- unique_copy(coll.begin(), coll.end(), // source
- ostream_iterator<int>(cout," ")); // destination
反转(Reverse)
std::reverse
- // 反转序列
- std::reverse(foo.begin(), foo.end());
std::reverse_copy
- // 将foo的反转序列拷贝到bar
- std::reverse_copy(std::begin(foo), std::end(foo), std::begin(bar));
循环(Rotate)
std::rotate
- // 循环使位置3处的元素成为第一个元素
- std::rotate(foo.begin(),foo.begin()+3,foo.end());
std::rotate_copy
- // 循环使位置3处的元素成为第一个元素,将循环的结果保存到bar中
- std::rotate(foo.begin(),foo.begin()+3,foo.end(),bar.begin());
随机移动(Random shuffle)
std::random_shuffle
- // 使用内置的随机数生成器随机移动元素
- std::random_shuffle ( foo.begin(), foo.end() );
- // 使用自定义的随机数生成器随机移动元素
- int myrandom (int i) { return std::rand()%i;}
- std::random_shuffle ( foo.begin(), foo.end(), myrandom);
std::shuffle
C++11- // 使用在<random>中定义的标准随机数生成器
- shuffle (foo.begin(), foo.end(), std::default_random_engine(seed));
划分(Partitions)
std::partition
- #include <iostream> // std::cout
- #include <algorithm> // std::partition
- #include <vector> // std::vector
- namespace ClassFoo{
- bool IsOdd (int i) { return (i%2)==1; }
- void Partition() {
- std::vector<int> foo;
- for (int i=1; i<10; ++i) foo.push_back(i); // 1 2 3 4 5 6 7 8 9
- std::vector<int>::iterator bound;
- bound = std::partition (foo.begin(), foo.end(), IsOdd);
- std::cout << "odd elements:";
- for (std::vector<int>::iterator it=foo.begin(); it!=bound; ++it)
- std::cout << ' ' << *it;
- std::cout << '\n';
- std::cout << "even elements:";
- for (std::vector<int>::iterator it=bound; it!=foo.end(); ++it)
- std::cout << ' ' << *it;
- std::cout << '\n';
- }
- }
- int main () {
- ClassFoo::Partition();
- return 0;
- }
输出:
odd elements: 1 9 3 7 5
even elements: 6 4 8 2
std::is_partitioned
C++11- #include <iostream> // std::cout
- #include <algorithm> // std::is_partitioned
- #include <array> // std::array
- namespace ClassFoo{
- bool IsOdd (int i) { return (i % 2)==1; }
- void IsPartitioned() {
- std::array<int,7> foo {1,2,3,4,5,6,7};
- // 打印内容
- std::cout << "foo:"; for (int& x:foo) std::cout << ' ' << x;
- if ( std::is_partitioned(foo.begin(),foo.end(),IsOdd) )
- std::cout << " (partitioned)\n";
- else
- std::cout << " (not partitioned)\n";
- // 划分区块:
- std::partition (foo.begin(),foo.end(),IsOdd);
- // 再次打印内容
- std::cout << "foo:"; for (int& x:foo) std::cout << ' ' << x;
- if ( std::is_partitioned(foo.begin(),foo.end(),IsOdd) )
- std::cout << " (partitioned)\n";
- else
- std::cout << " (not partitioned)\n";
- }
- }
- int main () {
- ClassFoo::IsPartitioned();
- return 0;
- }
输出:
foo: 1 2 3 4 5 6 7 (not partitioned)
foo: 1 7 3 5 4 6 2 (partitioned)
std::stable_partition
- bool IsOdd (int i) { return (i%2)==1; }
- std::stable_partition (foo.begin(), foo.end(), IsOdd);
std::partition_copy
C++11- bool IsOdd (int i) { return (i%2)==1; }
- std::partition_copy (foo.begin(), foo.end(), odd.begin(), even.begin(), IsOdd);
std::partition_point
C++11- // 返回划分临界点
- std::partition_point(foo.begin(),foo.end(),IsOdd);
合并(Merge)
std::merge
- // 合并两个范围的内容到一个容器中
- std::merge (foo1,foo1+5,foo2,foo2+5,foo3.begin());