目录
c++ umap 四种遍历方式
假如我们已有umap
unordered_map<int, int> umap;
F1:值传递
非 auto 形式:
for (pair<int, int> i:umap) {
cout << i.first << ' ' << i.second << "\n";
}
auto 形式:
for (auto i:umap) {
cout << i.first << " " << i.second << "\n";
}
F2:引用传递遍历
注意!(敲黑板)要加 const
const 在外的方式:
for (const pair<int, int> &i:umap) {
cout << i.first << " " << i.second << "\n";
}
const 在内的方式:
for (pair<const int, int> &i:umap) {
cout << i.first << " " << i.second << "\n";
}
F3:使用迭代器遍历
非 auto 形式:
for (unordered_map<int, int>::iterator it = umap.begin(); it != umap.end(); it++) {
cout << it->first << " " << it->second << "\n";
}
auto 形式:
for (auto it = umap.begin(); it != umap.end(); it++) {
cout << it->first << " " << it->second << "\n";
}
F4:结构化绑定(c++17特性,通常不用)
值传递:
for (auto [k, v]:umap) {
cout << k << " " << v << "\n";
}
引用式值传递:
for (auto& [k, v]:umap) {
cout << k << " " << v << "\n";
}
同样,只使用second,可以:
for (auto [_,v]:umap) {
cout << v << "\n";
}
拓展:auto是什么
auto 是一种根据后面的结果类型而随之固定类型的特殊变量。
一般在迭代器中容易用到。
例如:map<string,int>::iterator it = Mp.begin(); -> auto it = Mp.begin();