现代C++笔记(持续更新)
1.constexpr【C++11】
可以让临时变量在编译器就确定, 而不用每次运行的时候都走一遍
1
2
constexpr int len = 13;
char aaa[len];
2.if和switch的强化使用【C++17】
在17之前,一般if是这样的:if(条件){….}
现在可以这样if(临时变量;条件){….}
这主要可以解决之前临时变量作用域太广的问题
1
2
3
4
5
6
7
8
9
10
11
12
13
// C++17之前
int i = 5;
int j = 6;
if(i == j)
{
}
// C++17之后
if (int i = 5, int j = 5;i == j)
{
}
3.初始化列表initializer_list
可以让对象的初始化变成和初始化列表统一用{}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <initializer_list>
#include <vector>
#include <iostream>
class MagicFoo {
public:
std::vector<int> vec;
MagicFoo(std::initializer_list<int> list) {
for (std::initializer_list<int>::iterator it = list.begin();
it != list.end(); ++it)
vec.push_back(*it);
}
};
int main() {
// after C++11
MagicFoo magicFoo = {1, 2, 3, 4, 5};
std::cout << "magicFoo: ";
for (std::vector<int>::iterator it = magicFoo.vec.begin();
it != magicFoo.vec.end(); ++it)
std::cout << *it << std::endl;
}
如果没有initializer_list,我们初始化时需要这样
1
2
3
4
5
std::vector v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
但现在可以
1
std::vector v = { 1, 2, 3, 4 };
4.元组的使用【C++11】结构化绑定【C++17】
元组是主要是为了解决函数返回值太多的问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <tuple>
#include <iostream>
std::tuple<int, std::string> getInfo() {
return std::make_tuple(42, "Hello, World!");
}
int main() {
auto [num, text] = getInfo(); // 属于C++17的
std::cout << "Number: " << num << ", Text: " << text << std::endl;
// 输出:Number: 42, Text: Hello, World!
return 0;
}
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
#include <tuple>
#include <iostream>
#include <vector>
using Data = std::tuple<int, double, std::string>;
std::vector<Data> database = {
std::make_tuple(1, 3.14, "Circle"),
std::make_tuple(2, 2.71, "Square"),
std::make_tuple(3, 2.44, "Triangle")
};
//C++17之前
int main() {
for (const auto& row : database) {
std::cout << "ID: " << std::get<0>(row)
<< ", Area: " << std::get<1>(row)
<< ", Name: " << std::get<2>(row) << std::endl;
}
// 输出:
// ID: 1, Area: 3.14, Name: Circle
// ID: 2, Area: 2.71, Name: Square
// ID: 3, Area: 2.44, Name: Triangle
return 0;
}
//C++17
int main()
{
for (const auto& [id, area, name] : database) {
std::cout << "ID: " << id
<< ", Area: " << area
<< ", Name: " << name << std::endl;
}
// 输出:
// ID: 1, Area: 3.14, Name: Circle
// ID: 2, Area: 2.71, Name: Square
// ID: 3, Area: 2.44, Name: Triangle
return 0;
}
5.auto
1
2
3
4
5
6
7
8
9
10
// C++14可以编译过auto做lambda表达式的参数
auto add = [](auto x, auto y) -> int {
return x + y;
};
// C++20可以编译过auto做一般函数表达式的参数
auto sub(auto x, auto y)
{
return x - y;
}
auto
还不能用于推导数组类型
本文由作者按照 CC BY 4.0 进行授权