心血来潮,小试c++11

来源:互联网 发布:产品标贴制作软件 编辑:程序博客网 时间:2024/04/30 08:46

今天心血来潮,尝试玩一下c++11。话说这个标准都发布好几年了,c++14都出来了,c++17也快生出来了,还是赶紧摸一下c++11。本文使用实际业余工程使用到的代码片段,参考文章《stl::vector排序二例》。

示例1:

#include <vector>#include <string>#include <algorithm>#include <stdio.h>class foobar{public:    std::string token;    std::string item;    int number;        // 重载操作符    bool operator<(const foobar& rhs) { return (*this).token < rhs.token;};    bool operator>(const foobar& rhs) { return (*this).token > rhs.token;};    bool operator==(const foobar& rhs) { return (*this).token == rhs.token;} };int struct_element_sort(int argc, char* argv[]){    std::vector<foobar> vFo1o;        std::vector<foobar> vFoo = {        {"osd_1", "OSD111", 1},        {"osd_0", "OSD000", 0},        {"osd_2", "OSD222", 2},        {"osd_4", "OSD444", 4},        {"osd_3", "OSD333", 3},        {"osd_1", "OSD100100", 100},        };        printf("before sort: \n");    for (auto& val : vFoo)    {        printf("token: %s font: %d item: %s\n", val.token.c_str(), val.number, val.item.c_str());    }    // lambda表达式,升序    std::sort(vFoo.begin(),vFoo.end(),       [](const foobar& s1, const foobar& s2)        { return s1.token.compare(s2.token) < 0; });        printf("after sort--: \n");    for (auto& val : vFoo)    {        printf("token: %s font: %d item: %s\n", val.token.c_str(), val.number, val.item.c_str());    }        std::vector<foobar>::iterator unque_it  = std::unique(vFoo.begin(), vFoo.end());    vFoo.erase(unque_it, vFoo.end());    printf("after unque: \n");    for (auto& val : vFoo)    {        printf("token: %s font: %d item: %s\n", val.token.c_str(), val.number, val.item.c_str());    }    return 0;}


示例2:

////////////////////////////////////// 普通字符串// 分辨率 降序,即大的分辨率在前面bool sort_res(const std::string& s1, const std::string& s2){    //return s1.compare(s2) < 0;    int width1 = 0;    int height1 = 0;    int width2 = 0;    int height2 = 0;    sscanf(s1.c_str(), "%dx%d", &width1, &height1);    sscanf(s2.c_str(), "%dx%d", &width2, &height2);        // 宽相等,则比较高    if (width1 == width2)    {        return height1 > height2;    }    else     {        return width1 >width2;    }        return true;}int sort_string(){    std::vector<std::string> foo =             {                "1920x1080",                "1280x720",                "1920x1000",                "720x576",                "720x1080",            };        std::sort(foo.begin(), foo.end(), sort_res); // 复杂的就不用lambda        printf("after sort: \n");    for (auto val : foo)    {        printf("resolution: %s\n", val.c_str());    }        return 0;}

总结一下:

1、auto特性在遍历复杂的容器时,可以节省不少代码量。

2、使用基于范围的for循环遍历容器,也能节省代码量。

3、在一些场合下使用lambda,代码更精简。


李迟 2016.8.2 周二晚

0 0