如何在控制台上显示地图内容?
我有一个 map
声明如下:
map < string , list < string > > mapex ; list< string > li;
如何在控制台上显示存储在上述地图中的项目?
I have a map
declared as follows:
map < string , list < string > > mapex ; list< string > li;
How can I display the items stored in the above map on the console?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
更新(回到未来):使用 C++11 基于范围的 for 循环 –
Update (Back to the future): with C++11 range-based for loops –
这取决于您想要如何显示它们,但您始终可以轻松地迭代它们:
Well it depends on how you want to display them, but you can always iterate them easily:
我会尝试以下
I'd try the following
我在这里有点偏离主题...
我猜你想转储地图内容以进行调试。 我想提一下,下一个 gdb 版本(版本 7.0)将有一个内置的 python 解释器,gcc libstdc++ 将使用它来提供 stl 漂亮的打印机。 这是您的案例的一个示例
,结果是
Yay!
I'm a little off topic here...
I guess you want to dump the map content for debugging. I like to mention that the next gdb release (version 7.0) will have a built in python interpreter which will be used by the gcc libstdc++ to provide stl pretty printers. Here is an example for your case
which results in
Yay!
另一种形式,使用
:测试程序:
Another form, using
<algorithm>
:Test program:
您可以编写一个非常通用的重载函数,这有两个目的:
map
。<<
。该函数
cout <<
将适用于为typename
<< 的任何map
>skey_t
和value_t
。 在您的情况下,没有为value_t
(=list
) 定义它,因此您还必须定义它。本着类似的精神,您可以使用
因此,您可以:
using namespace std;
(或根据需要添加std::
)。<代码>cout<< 地图派克斯<< 结束;
<代码>cout<< 李<< endl;
请记住,如果刚刚定义的
<<
有任何其他可行的候选者(我认为没有,否则你可能不会问这个问题),它可能会优先于现在的。You can write a quite generic overloaded function, which is good for two purposes:
map
.<<
.The function is
cout <<
will work with anymap
for which<<
is defined fortypename
skey_t
andvalue_t
. In your case, this is not defined forvalue_t
(=list<string>
), so you also have to define it.In a similar spirit, you can use
So, you may:
using namespace std;
(or addstd::
as needed).cout << mapex << endl;
cout << li << endl;
Remember that if there is any other viable candidate for the
<<
s just defined (which I take there is not, otherwise you would likely not ask this question), it may take precedence over the present ones.如果您可以使用 C++11 功能,那么我认为 基于范围的 for 循环,如 顺磁羊角面包的答案提供了最具可读性的选项。 但是,如果您可以使用 C++17,那么您可以结合使用那些带有 结构化绑定 的循环可进一步提高可读性,因为您不再需要使用
first
和second
成员。 对于您的具体用例,我的解决方案如下所示:输出:
Coliru 上的代码
If you can use C++11 features, then I think range-based for loops as proposed in The Paramagnetic Croissant's answer provide the most readable option. However, if C++17 is available to you, then you can combine those loops with structured bindings to further increase readability, because you no longer need to use the
first
andsecond
members. For your specific use case, my solution would look as follows:Output:
Code on Coliru