您的位置:首页 > 编程语言 > C语言/C++

C++: 泛型算法

2013-04-24 16:18 162 查看
1. accumulate

ex: int sum = accumulate(vec.begin(), vec.end(), 42) sum设置为vec的元素之和再加上42.

ex: string sum = accumulate(v.begin(), v.end(), string("")); v里每个string元素都连起来,注意这里必须是string(""), 不能是""。

2. find_first_of(前面介绍过)

3. fill

ex: fill(vec.begin(), vec.end(), 0) 所有vec元素置为0

ex: fill(vec.begin(), vec.begin()+vec.size()/2, 10)

4. fill_n

ex: fill_n(vec.begin(), 10, 0) 从第一个元素开始的10个元素置为0。如果我们要写入10个元素,但这些元素却不存在---vec是空的,会导致运行错误,这个时候最好引入back_inserter.

ex: fill_n(back_inserter(vec), 10, 0)。相当于vec末尾调用vec.push_back(0)10次

5. replace_copy

ex: replace(ilst.begin(), ilst.end(), 0, 42)将ilst里所有0的实例替换成42,如果不想改变原来的系列,则调用replace_copy. replace_copy(ilst.begin(), ilst.end(), back_inserter(ivec), 0, 42). 这样ilst没有改变,ivec存储ilst的一份副本,而ilst内所有的0在ivec中都变成了42.

6. unique

比如要去除vector words里重复的元素,则

sort(words.begin(), words.end());

vector<string>::iterator end_unique = unique(words.begin(), words.end());

words.erase(end_unique, words.end());

unique删除相邻的重复元素,然后重新排列输入范围内的元素,并且返回一个迭代器,表示无重复的值范围的结束。

7. stable_sort

保留相等元素的原始相对位置

ex: stable_sort(words.begin(), words.end(), isShorter); isShorter函数自己写

8. count_if

统计长度不小于n的个数

ex: count_if(words.begin(), words.end(), GT6) GT6函数自己写

9. lst.merge(lst2), lst.merge(lst2, comp).

默认comp为<, lst2将被删除

10. lst.reverse();

11. lst.sort();

12. lst.splice(iter, lst2), lst.splice(iter, lst2, iter2), lst.splice(iter, beg, end)

泛型算法有100多种,这里只是一些,还有更多以后再学
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: