我有一个像这样的map
:
map<string, pair<string, string>> myMap;
我已经使用以下代码向我的地图中插入了一些数据:
myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));
我现在该如何打印出我的映射表中的所有数据?
我有一个像这样的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";
}
const auto&
以避免元素的复制。希望这就是你想要的。除此之外,最后一个并不更慢。 - Armen Tsirunyan自从C++17以来,您可以使用range-based for循环和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& 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"));
&
可以避免在循环迭代期间进行复制。 - CyprUSmap<string ,string> :: iterator it;
然后通过使用从 myMap.begin()
到 myMap.end()
的迭代器循环遍历 map,并使用 it->first
来打印出 map 中的键和 it->second
来打印出值。 map<string ,string> :: iterator it;
for(it=myMap.begin();it !=myMap.end();++it)
{
std::cout << it->first << ' ' <<it->second;
}
for(auto& x:myMap){
cout<<x.first<<" "<<x.second.first<<" "<<x.second.second<<endl;
}
cout::operator<<
应用于它们。这并不难,真的。 - user529758