栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【C++ Primer】 第十章 泛型算法 书上代码 sort 和 unique erase lambda 三种写法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【C++ Primer】 第十章 泛型算法 书上代码 sort 和 unique erase lambda 三种写法

书上的代码 都敲了一边

读

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 
    vectorlist{1,3,5,23,3,4,0,0,32};
    replace(list.begin(),list.end(),0,42);
    //使用back_insterter按需要增长目标序列
    vectorivec;
    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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/991236.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号