Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Pair as a key in map using c++

I want to know how can insert pair in map using c++, here's my code:

map< pair<int, string>, int> timeline;

I tried to insert it using:

timeline.insert(pair<pair<int, string> , int>(make_pair(12, "str"), 33);
//and
timeline.insert(make_pair(12, "str"), 33);

but I got error

\main.cpp|66|error: no matching function for call to 'std::map<std::pair<int, std::basic_string<char> >, int&>::insert(std::pair<int, const char*>, int)'|


2 Answers

std::map::insert expects std::map::value_type as its argument, i.e. std::pair<const std::pair<int, string>, int>. e.g.

timeline.insert(make_pair(make_pair(12, "str"), 33));

or simpler as

timeline.insert({{12, "str"}, 33});

If you want to construct element in-place you can also use std::map::emplace, e.g.

timeline.emplace(make_pair(12, "str"), 33);

LIVE

like image 116
songyuanyao Avatar answered Sep 07 '26 18:09

songyuanyao


When in doubt, simplify.

auto key = std::make_pair(12, "str");
auto value = 33;

timeline.insert(std::make_pair(key, value));
like image 25
R Sahu Avatar answered Sep 07 '26 20:09

R Sahu



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!