心血来潮,小试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;}
////////////////////////////////////// 普通字符串// 分辨率 降序,即大的分辨率在前面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
- 心血来潮,小试c++11
- 心血来潮
- 心血来潮
- 心血来潮
- 心血来潮
- 心血来潮
- 心血来潮
- 11月20日 心血来潮
- 今天心血来潮,写了个python的小爬虫
- 心血来潮?不!
- 心血来潮学五笔
- 心血来潮小记
- 心血来潮001
- c语言小试
- 心血来潮有个比喻
- 心血来潮之测试问题
- 心血来潮 回味人生
- 心血来潮,开通了博客
- 扫雷App的实现
- spoj 687 repeats
- android 6.0的权限问题
- Codeforces #280 Div.2 E.Vanya and Field 数学,数论
- Android扫描枪(PDA)开发
- 心血来潮,小试c++11
- rf中对于有滚动条的页面中元素的处理
- POJ 3278 抓牛简单广搜
- 个人总结——studio的常用插件的使用(工作实践)
- 基于QT实现对网络摄像头数据的显示
- 深入理解HashMap(及hash函数的真正巧妙之处)
- Cloudera Manager 5安装
- 配置自定义标签可以有三种方式
- POJ 1611 The Suspects (并查集)