Cut*_*ute 32 c++ dictionary stl stdmap
我有一张地图
map < string , list < string > > mapex ; list< string > li;
Run Code Online (Sandbox Code Playgroud)
如何在控制台上显示上述地图项.
The*_*ant 38
更新(回到未来):使用C++ 11基于范围的for循环 -
std::map<Key, Value> m { ... /* initialize it */ ... };
for (const auto &p : m) {
std::cout << "m[" << p.first << "] = " << p.second << '\n';
}
Run Code Online (Sandbox Code Playgroud)
Sku*_*del 24
那么它取决于你想要如何显示它们,但你总是可以轻松地迭代它们:
typedef map<string, list<string>>::const_iterator MapIterator;
for (MapIterator iter = mapex.begin(); iter != mapex.end(); iter++)
{
cout << "Key: " << iter->first << endl << "Values:" << endl;
typedef list<string>::const_iterator ListIterator;
for (ListIterator list_iter = iter->second.begin(); list_iter != iter->second.end(); list_iter++)
cout << " " << *list_iter << endl;
}
Run Code Online (Sandbox Code Playgroud)
Jar*_*Par 12
我试试以下
void dump_list(const std::list<string>& l) {
for ( std::list<string>::const_iterator it = l.begin(); l != l.end(); l++ ) {
cout << *l << endl;
}
}
void dump_map(const std::map<string, std::list<string>>& map) {
for ( std::map<string,std::list<string>>::const_iterator it = map.begin(); it != map.end(); it++) {
cout << "Key: " << it->first << endl;
cout << "Values" << endl;
dump_list(it->second);
}
Run Code Online (Sandbox Code Playgroud)
我在这里有点偏离主题......
我想你想要转储地图内容进行调试.我想提一下,下一个gdb版本(7.0版)将有一个内置的python解释器,gcc libstdc ++将使用它来提供stl漂亮的打印机.以下是您案例的示例
#include <map>
#include <map>
#include <list>
#include <string>
using namespace std;
int main()
{
typedef map<string, list<string> > map_type;
map_type mymap;
list<string> mylist;
mylist.push_back("item 1");
mylist.push_back("item 2");
mymap["foo"] = mylist;
mymap["bar"] = mylist;
return 0; // stopped here
}
Run Code Online (Sandbox Code Playgroud)
结果
(gdb) print mymap
$1 = std::map with 2 elements = {
["bar"] = std::list = {
[0] = "item 1",
[1] = "item 2"
},
["foo"] = std::list = {
[0] = "item 1",
[1] = "item 2"
}
}
Run Code Online (Sandbox Code Playgroud)
好极了!
| 归档时间: |
|
| 查看次数: |
80451 次 |
| 最近记录: |