6
votes

I am trying to have three elements in an unordered_map. I tried the following code

#include <iostream>
#include <string>
#include <algorithm>
#include <boost/unordered_map.hpp>

typedef boost::unordered_map<int, std::pair<int, int>> mymap;
mymap m;

int main(){
//std::unordered_map<int, std::pair<int, int> > m;
m.insert({3, std::make_pair(1,1)});
m.insert({4, std::make_pair(5,1)});
for (auto& x: m)
    std::cout << x.first << ": "<< x.second << std::endl;

}

but I get many errors in the print statement something like

‘std::pair’ is not derived from ‘const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’ std::cout << x.first << ": "<< x.second << std::endl;

1
Why not create a structure and add that instead of the pair? I think code would be more readable.Oliver Ciappara
The insert is ok, because that is where I see a problem. It should be m.insert(3, std::make_pair(1,1)); Without {}Dragos Pop
The title says "unordered map to have three elements". I only see two elements in the code though. Or do you mean that a map which maps an integer to a pair of integers has a value type with three ints in it?Martin Bonner supports Monica
@MartinBonner I mean a key have two ints as valuesAwaitedOne
@DragosPop Does {} have any side effectAwaitedOne

1 Answers

8
votes

The problem in your printing statement. It should be like this:

std::cout << x.first << ": "<< x.second.first << ","<< x.second.second  << std::endl;
_______________________________^^^^^^^^^^^^^^__________^^^^^^^^^^^^^^^_______________

You can not just print std::pair directly. You need to print each item separately.

There is no ostream& operator<< overload for std::pair but there is one for int.