读书上的代码 都敲了一边
count 和 accumulate
#include#include #include #include using namespace std; int main () { vector a = {1,1,11,1,3,3,4,51,2}; auto it = accumulate(a.cbegin(), a.cend(), 0); cout << it << endl; return 0; }
fill.main
#include#include #include using namespace std; // bool i { // return ; // } int main () { //下面的代码是错误的 vector vec; //空向量 //灾难:修改vec中的10个(不存在)元素 fill_n(vec.begin(),10,0); for(auto i : vec) { cout << i << endl; } return 0; }
replace 和 copy
#include#include #include #include using namespace std; int main () { vector vec; //空向量 auto it = back_inserter(vec); //通过它赋值会将元素添加到vec中 *it = 42; //vec中现在有一个元素,值为42 vector vec2; //正确:back_inserter创一个插入迭代器,可用来项vec添加元素 fill_n(back_inserter(vec2),10,0); //添加10个元素到vec //每次赋值,会在迭代器上调用push_back int a1[]={0,1,2,3,4,5,6,7,8,9}; int a2[sizeof(a1)/sizeof(*a1)]; //a2与a1大小一样 //ret指向拷贝到a2的尾元素之后的位置 auto ret = copy(begin(a1),end(a1),a2);//把a1的内容拷贝给a2 //将所有值为0的元素改为42 vector list{1,3,5,23,3,4,0,0,32}; replace(list.begin(),list.end(),0,42); //使用back_insterter按需要增长目标序列 vector ivec; replace_copy(list.cbegin(),list.cend(),back_inserter(ivec),0,42); //上面的语句调用后,ilst并未改变,ivec包含ilst的一份拷贝 //不过原来在ilst中值为0的元素在ivec中都变成了42 for(auto it : ivec) { cout << it << endl; } return 0; }
sort 和 unique erase lambda
#include#include #include #include #include using namespace std; // bool isShorter(const string &s1, const string &s2){ // return s1.size() < s2.size(); // } void elimDups(vector & words) { //按字典顺序排序words,以便查找重复单词 sort(words.begin(), words.end()); //版本 1 sort(words.begin(), words.end(),[]( //lambda 版本 const string &s1,const string &s2){ return s1.size() < s2.size();}); // sort(words.begin(), words.end(),isShorter); // 大小排序后的版本 //unique消除相邻的重复项 //排列在范围的前部,返回指向不重复区域之后一个位置的迭代器 auto end_unique = unique(words.begin(), words.end()); words.erase(end_unique, words.end()); } int main () { vector words ={ "the","quick","red","fox","jumps","over","the","slow","red","turtle" }; elimDups(words); for(auto it : words) { cout << it << endl; } return 0; }



