如何在 C++ 中对 Map 进行迭代
-
使用
while
循环在std::map
元素上迭代 -
使用传统的
for
循环在std::map
元素上迭代 -
使用基于范围的
for
循环迭代std::map
元素 -
使用基于范围的 for 循环迭代
std::map
键-值对
本文将解释如何在 C++ 中使用多种方法对 map
进行迭代。
使用 while
循环在 std::map
元素上迭代
首先,我们定义一个临时映射结构 tempMap
,并在其中填充任意的键/值对,我们将在 stdout
输出,以更好地展示建议的解决方案。
#include <iostream>
#include <map>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::map;
int main() {
map<int, string> tempMap = {{1, "Apple",},
{2, "Banana",},
{3, "Mango",},
{4, "Raspberry",},
{5, "Blackberry",},
{6, "Cocoa",}};
auto iter = tempMap.begin();
while (iter != tempMap.end()) {
cout << "[" << iter->first << ","
<< iter->second << "]\n";
++iter;
}
cout << endl;
return 0;
}
输出:
[1,Apple]
[2,Banana]
[3,Mango]
[4,Raspberry]
[5,Blackberry]
[6,Cocoa]
请注意,我们使用 auto
类型指定符来声明 std::map
迭代器,因为为了可读性,推荐使用这种方法。它是 map<int, string>::iterator
,可以显式指定。
使用传统的 for
循环在 std::map
元素上迭代
现在,让我们用传统的 for
迭代来实现同样的循环,这可以说是在可读性上最差的。
#include <iostream>
#include <map>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::map;
int main() {
map<int, string> tempMap = {{1, "Apple",},
{2, "Banana",},
{3, "Mango",},
{4, "Raspberry",},
{5, "Blackberry",},
{6, "Cocoa",}};
for (auto iter = tempMap.begin(); iter != tempMap.end(); ++iter){
cout << "[" << iter->first << ","
<< iter->second << "]\n";
}
cout << endl;
return 0;
}
使用基于范围的 for
循环迭代 std::map
元素
一段时间以来,基于范围的循环一直是 C++ 程序员的普遍选择。如果你的编译器支持 C++11 版本,那么你就不用再考虑传统的繁琐循环了,可以欣赏下面这个例子的优雅。
#include <iostream>
#include <map>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::map;
int main() {
map<int, string> tempMap = {{1, "Apple",},
{2, "Banana",},
{3, "Mango",},
{4, "Raspberry",},
{5, "Blackberry",},
{6, "Cocoa",}};
for (const auto &item : tempMap) {
cout << "[" << item.first << "," << item.second << "]\n";
}
cout << endl;
return 0;
}
使用基于范围的 for 循环迭代 std::map
键-值对
这个版本从 C++17 标准开始定义,以在关联容器中提供更灵活的迭代。与之前的例子相比,该方法的主要优势在于方便地访问 map
结构中的键值,这也保证了程序员更好的可读性。
#include <iostream>
#include <map>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::map;
int main() {
map<int, string> tempMap = {{1, "Apple",},
{2, "Banana",},
{3, "Mango",},
{4, "Raspberry",},
{5, "Blackberry",},
{6, "Cocoa",}};
for (const auto& [key, value] : tempMap) {
cout << "[" << key << "," << value << "]\n";
}
cout << endl;
return 0;
}
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn