如何显示地图内容?

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)

  • @triclosan:也许,或者编译器会为你优化它.没有尝试就不可能说.在宏观方案中,我们使用的是标准的iostream控制台输出,这种输出在性能上远远超过额外对象迭代器对象的任何成本. (5认同)

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)


Mai*_*ann 5

我在这里有点偏离主题......

我想你想要转储地图内容进行调试.我想提一下,下一个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)

好极了!