1.移除性算法remove
首先查找给定值第一个位置,然后遍历后面的元素,将非移除元素拷贝到前面,覆盖前面的元素。
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
using namespace std;
void print_element(int n) {
cout << n << " ";
}
int main(void) {
int a[] = { 1, 3, 2, 3, 4, 5 };
vector<int> v(a, a+6);
list<int> l(15);
for_each(v.begin(), v.end(), print_element);
cout << endl;
/*remove(v.begin(), v.end(), 3);
for_each(v.begin(), v.end(), print_element);
cout << endl;*/
v.erase(remove(v.begin(), v.end(), 3), v.end());
for_each(v.begin(), v.end(), print_element);
cout << endl;
return 0;
}
执行结果:
2.变序rotate
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
using namespace std;
void print_element(int n) {
cout << n << " ";
}
int main(void) {
int a[] = { 1, 3, 2, 3, 4, 5 };
vector<int> v(a, a+6);
list<int> l(15);
for_each(v.begin(), v.end(), print_element);
cout << endl;
rotate(v.begin(), v.begin()+2, v.end()-1);
for_each(v.begin(), v.end(), print_element);
cout << endl;
return 0;
}
/*
* list<int> l
* l.end()-1
* 链表不支持随机访问+,-,+=,-=:error
* ++,--:ok*/
执行结果:3.排序算法sort
4.已序区间算法
lower_bound:(应用于有序区间)搜索第一个“大于等于给定值”的元素,如果要插入给定值保持区间有序性,返回第一个可插入位置
upped_bound:(应用于有序区间)搜索第一个“大于给定值”的元素,如果要插入给定值,保持区间有序性,返回最后一个可插入的位置
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
using namespace std;
void print_element(int n) {
cout << n << " ";
}
int main(void) {
int a[] = { 1, 10, 10, 14, 15, 16 };
vector<int> v(a, a+6);
list<int> l(15);
for_each(v.begin(), v.end(), print_element);
cout << endl;
auto it = lower_bound(v.begin(), v.end(), 10);
if(v.end() != it) {
cout << it - v.begin() << endl;
}
it = upper_bound(v.begin(), v.end(), 10);
if(v.end() != it) {
cout << it - v.begin() << endl;
}
v.insert(it,55);
for_each(v.begin(), v.end(), print_element);
cout << endl;
return 0;
}
执行结果:
5.数值算法accumulate
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <numeric>
using namespace std;
void print_element(int n) {
cout << n << " ";
}
int mult(int a,int b) {
return a*b;
}
int main(void) {
int a[] = { 1, 2, 3, 4, 5, 6 };
vector<int> v(a, a+6);
for_each(v.begin(), v.end(), print_element);
cout << endl;
//累加
cout << accumulate(v.begin(), v.end(), 0) <<endl;
//累乘
cout << accumulate(v.begin(), v.end(), 1, mult) << endl;
return 0;
}