Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print map in c++ without using iterator

Tags:

c++

stl

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 ?

like image 471
Undefined Behaviour Avatar asked Sep 14 '26 00:09

Undefined Behaviour


1 Answers

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

like image 142
Andrew Avatar answered Sep 16 '26 15:09

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!