如何打印出 C++ 地图值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14070940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I print out C++ map values?
提问by laxxers
I have a map
like this:
我有一个map
这样的:
map<string, pair<string,string> > myMap;
And I've inserted some data into my map using:
我已经使用以下方法将一些数据插入到我的地图中:
myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));
How can I now print out all the data in my map?
我现在如何打印地图中的所有数据?
回答by Armen Tsirunyan
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";
}
In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator
. You can use auto
在 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";
}
Note the use of cbegin()
and cend()
functions.
注意cbegin()
和cend()
函数的使用。
Easier still, you can use the range-based for loop:
更简单的是,您可以使用基于范围的 for 循环:
for(auto elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}
回答by Jerry Coffin
If your compiler supports (at least part of) C++11 you could do something like:
如果您的编译器支持(至少部分)C++11,您可以执行以下操作:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
For C++03 I'd use std::copy
with an insertion operator instead:
对于 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"));
回答by honk
Since C++17you can use range-based for loopstogether with structured bindingsfor iterating over your map. This improves readability, as you reduce the amount of needed first
and second
members in your code:
从C++17 开始,您可以使用基于范围的 for 循环和结构化绑定来迭代您的地图。这提高了可读性,因为您减少了代码中所需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;
Output:
输出:
m[x] = (a, b)
m[y] = (c, d)
m[x] = (a, b)
m[y] = (c, d)