#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()
代码:
/* algorithm.cc
* 2014/09/02 update
*/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std; void print(int elem) {
cout << elem << endl;
} int main() {
vector<int> v;
vector<int>::iterator pos; for(int i = ; i >= ; i--)
v.push_back(i); //max_element
pos = max_element(v.begin(), v.end());
cout << "the max element is: " << *pos << endl;
//min_element
pos = min_element(v.begin(), v.end());
cout << "the min element is: " << *pos << endl; //sort
sort(v.begin(), v.end()); //find
pos = find(v.begin(), v.end(), ); //reverse
reverse(pos, v.end()); for(pos = v.begin(); pos != v.end(); pos++)
cout << "Content of vector: " << *pos << " " << endl; //copy
vector<int> v2;
vector<int>::iterator pos1; v2.resize(v.size());
copy(v.begin(), v.end(), v2.begin());
cout << "Pre:" << endl;
copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " ")); //remove
vector<int>::iterator end = remove(v2.begin(), v2.end(), );
cout << endl << "After remove(v2.begin(), v2.end(), 5) : " << endl;
copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " "));
v2.erase(end, v2.end());
cout << endl << "After erase(end, v2.end()) : " << endl;
copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
//也可以使用v2.erase(remove(v2.begin(), v2.end(), 5), v2.end())) //for_each()
cout << "cout from for_each():" << endl;
for_each(v2.begin(), v2.end(), print); return ;
}
输出:
$ ./a.exe
the max element is:
the min element is:
Content of vector:
Content of vector:
Content of vector:
Content of vector:
Content of vector:
Content of vector:
Pre: After remove(v2.begin(), v2.end(), ) : After erase(end, v2.end()) : cout from for_each():