-1

I am attempting to write a general utility code file that I can include whenever I want to for debugging purposes, instead of having to write the same code over and over again. Among those utility functions is an overloaded operator to output maps in C++.

template<typename T, typename U>
ostream &operator << (ostream &o, map<T, U> m) {
    for (typename map<T, U>::iterator it = m.begin(); it != m.end(); it++) {
        o << "{" << it->first << "} = [" << it->second << "]" << endl;
    }
    return o;
}

This function works, but for some reason the first element in the map always gets displayed last. For example, if I initialize a map with the following code:

map<string, int> test;
test["one"] = 1;
test["two"] = 2;
test["three"] = 3;

and then try to output it using the above function, it gets printed as:

{two} = [2]
{three} = [3]
{one} = [1]

It's not a huge deal since it's just output, but I'm wondering why this happens. Does this affect operations that are actually dependent on order, or is it just funky output?

  • 1
    The ordering of the keys is a template parameter. Insertion order is irrelevant. – Ulrich Eckhardt Oct 24 '22 at 20:32
  • 3
    Can't reproduce, it prints the correct order `one` -> `three` -> `two` for me: https://godbolt.org/z/Gx5cxjfWz – Yksisarvinen Oct 24 '22 at 20:33
  • When I run this, I get `{one}, {three}, {two}`. Which is expected, because by default `std::map` is ordered lexicographically by its keys (i.e. it is *not* insertion ordered, which seems to be what you are expecting). – 0x5453 Oct 24 '22 at 20:33
  • 3
    That is funky that it is printing backwards for you. Should be printing one three two, not two three one. – Eljay Oct 24 '22 at 20:40
  • 1
    A very minimal effort would be to provide the actual output you get. The above code won't produce the output in shown order. Also, you should read documentation of a class/function when you don't knows what it does. C++ is not a language you should use for guesswork. – Phil1970 Oct 24 '22 at 21:20

1 Answers1

2

This is because a std::map in C++ is an ordered container which is sorted by it's keys values ascending by default.

Bemwa Malak
  • 1,182
  • 1
  • 5
  • 18