简体   繁体   中英

how to print map in c++ without using iterator

Is it possible to print map in c++ without using iterator ? something like

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

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

Is it necessary to make iterator for printing map value ?

If you simply want to avoid typing out the iterator boilerplate, you can use a range-for loop to print each item:

#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;
}

Live example: http://coliru.stacked-crooked.com/a/b5f7eac88d67dafe

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

Obviously, this uses the map's iterators under the hood...

Is it necessary to make iterator for printing map value ?

Yes you need them, you can't know what keys been inserted in advance. And your code is not correct, think about

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM