心血来潮,小试c++11

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

示例1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
////////////////////////////////////
// 普通字符串
// 分辨率 降序,即大的分辨率在前面
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 周二晚

  • 本文作者:李迟
  • 版权声明:原创文章,版权归署名作者,转载建议注明出处(当然不注明亦可)。
  • 本文链接:/my-library/new-to-c11.html