C++代码知识整理

💡 面向就业的C++代码知识整理

C++代码知识

For

for-each

for specific value

Reference (&)

Use Reference in Function Parameter

Iterator

The magical way to use trravelsal in STL (vector, map, list).

Forward & Backward

1
2
3
4
5
6
7
8
9
10
11
12
13
# forward
vector<int> v {1, 3, 5, 7 ,8};
vector<int>::iterator i;
for (i = v.begin(); i != v.end(); ++i) {
count << *i; # use *i to show the item
} # 13578

# backward
vector<int> v {1, 3, 5, 7 ,8};
vector<int>::reverse_iterator i;
for (i = v.rbegin(); i != v.rend(); ++i) {
count << *i; # use *i to show the item
} # 87531

C++ 11

Emplace

why emplace function have a better efficiency

Emplace can just create the data at the suitable location. But insert need to create first and then move to the suitable.

Auto

Before c++11, auto exists but is useless.

On c++11, auto is used to infer data type. For example, if you have a very long data type name, you can use auto to replace it.

1
2
3
4
# you have a unorder_map name umap and you want to create a iterator
std::unordered_map<int, int>::iterator iter = umap.begin();
# now you can replace as
auto iter = umap.begin();

Data Structure

Map

hashmap

There is no standard hashmap before c++11. So c++11 adds hashmap into its standard library and names ‘unorder_map’

1
2
3
4
5
6
# Initialization
std::unordered_map<int, int> umap;

# add item
umap.emplace(1, 2)
umap.emplace(2, 3)