如何在不使用迭代器的情况下在 C++ 中打印地图

how to print map in c++ without using iterator

本文关键字:C++ 情况下 打印 地图 迭代器      更新时间:2023-10-16

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

map <int, int>m;
m[0]=1;
m[1]=2;
for(int i =0; i<m.size(); i++)
    std::cout << m[i];

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

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

#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

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

显然,这在引擎盖下使用了地图的迭代器......

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

是的,您需要它们,您无法知道提前插入了哪些键。而且你的代码不正确,想想

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.