心血来潮,小试c++11

今天心血来潮,尝试玩一下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 周二晚

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值