unordered_map to have three elements

自闭症网瘾萝莉.ら 提交于 2019-12-10 13:56:08

问题


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:


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.



来源:https://stackoverflow.com/questions/41675259/unordered-map-to-have-three-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!