如何在不使用迭代器的情况下在c ++中打印map

时间:2016-04-21 10:48:14

标签: c++ stl

是否可以在不使用迭代器的情况下以c ++打印地图?

之类的东西
map <int, int>m;
m[0]=1;
m[1]=2;

for(int i =0; i<m.size(); i++)
    std::cout << m[i];

是否需要制作用于打印地图值的迭代器?

2 个答案:

答案 0 :(得分:3)

如果您只是想避免输入迭代器样板,可以使用 range-for loop 来打印每个项目:

#include <iostream>
#include <map>

int main() {
    std::map<int,std::string> m = {{1, "one"}, {2, "two"}, {3, "three"}};

    for (const auto& x : m) {
        std::cout << x.first << ": " << x.second << "\n";
    }

    return 0;
}

实例:http://coliru.stacked-crooked.com/a/b5f7eac88d67dafe

Ranged-for:http://en.cppreference.com/w/cpp/language/range-for

显然,这会使用地图下的地图迭代器......

答案 1 :(得分:1)

  

是否需要制作用于打印地图值的迭代器?

是的,你需要它们,你不能事先知道插入了什么键。你的代码不正确,想想

map <int, int>m;
m[2]=1;
m[3]=2;

for(int i =0; i<m.size(); i++)
    std::cout << m[i];  // oops, there's not m[0] and m[1] at all.
                        // btw, std::map::operator[] will insert them in this case.