我有一个像这样的
map
:
map<string, pair<string, string>> myMap;
我已经使用以下方法将一些数据插入到我的地图中:
myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));
我现在如何打印出地图中的所有数据?
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++11,你可以这样做:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
对于 C++03,我将使用
std::copy
和插入运算符来代替:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
自 C++17 起,您可以使用 range-based for loops 和 structured bindings 迭代你的地图。这提高了可读性,因为您减少了代码中所需的
first
和 second
成员的数量:
std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };
for (const auto &[k, v] : myMap)
std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;
输出:
m[x] = (a, b)
m[y] = (c, d)
您可以像这样尝试基于范围的循环:
for(auto& x:myMap){
cout<<x.first<<" "<<x.second.first<<" "<<x.second.second<<endl;
}
最简单的方法是先声明一个迭代器为
map<string ,string> :: iterator it;
然后通过使用迭代器从
myMap.begin()
到 myMap.end()
在地图上循环打印出来,并打印出地图中的键和值对,其中 it->first
为键,it->second
为值。
map<string ,string> :: iterator it;
for(it=myMap.begin();it !=myMap.end();++it)
{
std::cout << it->first << ' ' <<it->second;
}