一、非变异算法
是一组不破坏操作数据的模板函数,用来对序列数据进行逐个处理、元素查找、子序列搜索、统计和匹配。非变异算法具有极为广泛的适用性,基本上可应用与各种容器。
1. 查找容器元素 find
vector
result = find( v1.begin(), v1.end(), num_to_find );
2. 条件查找容器元素 find_if
bool divby5(int x) { return x % 5 ? 0 : 1; }
vector
ilocation=find_if(v.begin(),v.end(),divby5);
3. 统计等于某值的容器元素个数 count
count(l.begin(),l.end(),value)
4. 条件统计 count_if
count_if(l.begin(),l.end(),pred)。谓词pred含义同find_if中的谓词。例子可以参考例2.
5. 子序列搜索 search
search算法函数在一个序列中搜索与另一序列匹配的子序列。参数分别为一个序列的开始位置,结束位置和另一个序列的开始,结束位置。
函数原型:search(v1.begin(),v1.end(),v2.begin(),v2.end());
6. 重复元素子序列搜索 search_n
search_n算法函数搜索序列中是否有一系列元素值均为某个给定值的子序列。函数原型:search_n(v.begin(),v.end(),3,8),在v中找到3个连续的元素8。
7. 最后一个子序列搜索 find_end
函数原型find_end(v1.begin(),v1.end(),v2.begin(),v2.end());在V1中要求的位置查找V2中要求的序列。
二、变异算法
是一组能够修改容器元素数据的模板函数。copy(v.begin(),v.end(),l.begin());将v中的元素复制到l中。
1. 元素复制 copy
copy(v.begin(),v.end(),l.begin());
2. 元素变换 transfrom
函数原型:transform(v.begin(),v.end(),l.begin(),square);也是复制,但是要按某种方案复制。
int square (int x) { return x * x; }
3. 替换 replace
replace(v.begin(),v.end(),25,100);
4. 条件替换 replace_if
函数原型:replace_if(v.begin(),v.end(),odd,100);
bool odd (int x) { return x % 2; }
5. n次填充fill_n
函数原型fill_n(v.begin(),5,-1);向从v.begin开始的后面5个位置填入-1。
6. 随机生成n个元素 generate
函数原型:generate_n(v.begin(),5,rand);向从v.begin开始的后面5个位置随机填写数据。
7. 条件移除 remove_if
返回值相当于移除满足条件的元素后形成的新向量的end()值。
函数原型:remove_if(v.begin(),v.end(),even);
8. 剔除连续重复元素 unique
函数原型:unique(v.begin(),v.end());
三、排序算法
1. 创建堆 make_heap
2. 元素入堆 push_heap(默认插入最后一个元素)
3. 元素出堆 pop_heap (与push_heap一样,pop_heap必须对堆操作才有意义)
make_heap(v.begin(), v.end());
v.push_back(20);
push_heap(v.begin(),v.end());
pop_heap(v.begin(),v.end());
4. 堆排序 sort_heap
使用:
make_heap(v.begin(),v.end());
sort_heap(v.begin(),v.end());
5. 排序 sort
函数原型:sort(v.begin(),v.end());