#include <algorithm>
1. max_element(v.begin(), v.end());
注意,所有的区间全部是半开区间,如果数组包含20~40,通过find找出25,和35的positon,但是max_element(pos25, pos35)得到的是34.
2. min_element(v.begin(), v.end());
3. find(v.begin(), v.end(), 3);
4. sort(v.begin(), v.end());
5. reverse(pos, v.end();
6. copy(v1.begin(), v1.end(), v2.begin());
7. remove(v1.begin(), v1.end(), 3);
8. for_each()
代码:
1 /* algorithm.cc 2 * 2014/09/02 update 3 */ 4 #include <iostream> 5 #include <vector> 6 #include <list> 7 #include <algorithm> 8 #include <iterator> 9 using namespace std; 10 11 void print(int elem) { 12 cout << elem << endl; 13 } 14 15 int main() { 16 vector<int> v; 17 vector<int>::iterator pos; 18 19 for(int i = 6; i >= 1; i--) 20 v.push_back(i); 21 22 //max_element 23 pos = max_element(v.begin(), v.end()); 24 cout << "the max element is: " << *pos << endl; 25 //min_element 26 pos = min_element(v.begin(), v.end()); 27 cout << "the min element is: " << *pos << endl; 28 29 //sort 30 sort(v.begin(), v.end()); 31 32 //find 33 pos = find(v.begin(), v.end(), 3); 34 35 //reverse 36 reverse(pos, v.end()); 37 38 for(pos = v.begin(); pos != v.end(); pos++) 39 cout << "Content of vector: " << *pos << " " << endl; 40 41 //copy 42 vector<int> v2; 43 vector<int>::iterator pos1; 44 45 v2.resize(v.size()); 46 copy(v.begin(), v.end(), v2.begin()); 47 cout << "Pre:" << endl; 48 copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " ")); 49 50 //remove 51 vector<int>::iterator end = remove(v2.begin(), v2.end(), 5); 52 cout << endl << "After remove(v2.begin(), v2.end(), 5) : " << endl; 53 copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " ")); 54 v2.erase(end, v2.end()); 55 cout << endl << "After erase(end, v2.end()) : " << endl; 56 copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " ")); 57 cout << endl; 58 //也可以使用v2.erase(remove(v2.begin(), v2.end(), 5), v2.end())) 59 60 //for_each() 61 cout << "cout from for_each():" << endl; 62 for_each(v2.begin(), v2.end(), print); 63 64 return 0; 65 }
输出:
$ ./a.exe the max element is: 6 the min element is: 1 Content of vector: 1 Content of vector: 2 Content of vector: 6 Content of vector: 5 Content of vector: 4 Content of vector: 3 Pre: 1 2 6 5 4 3 After remove(v2.begin(), v2.end(), 5) : 1 2 6 4 3 3 After erase(end, v2.end()) : 1 2 6 4 3 cout from for_each(): 1 2 6 4 3