我有一个像这样的 map
:
map<string, pair<string,string> > myMap;
我已经在我的 map 中插入了一些数据:
myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));
我现在如何打印 map 中的所有数据?
最佳答案
for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
在 C++11 中,您无需拼写 map<string, pair<string,string> >::const_iterator
.您可以使用auto
for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
注意 cbegin()
的使用和 cend()
功能。
更简单的是,您可以使用基于范围的 for 循环:
for(const auto& elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}
关于c++ - 如何打印出 C++ 映射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14070940/