Undefined Behaviour
Undefined Behaviour

Reputation: 749

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 ?

Upvotes: 3

Views: 18907

Answers (2)

Andrew
Andrew

Reputation: 5352

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...

Upvotes: 10

songyuanyao
songyuanyao

Reputation: 172904

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.

Upvotes: 1

Related Questions