user5693629
user5693629

Reputation:

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)'|

Upvotes: 2

Views: 3594

Answers (3)

songyuanyao
songyuanyao

Reputation: 173044

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

Upvotes: 6

Sri Harsha
Sri Harsha

Reputation: 21

Simply use the traditional way:

timeline[key] = value;

For instertion and retrival of pair:

 timeline[{1,"stackOverFlow"}] = 69;
   
   for(auto i: timeline)
        {
            
            cout<< i.first.first;
            cout<< i.first.second;
            cout<< i.second;
        }

Upvotes: 1

R Sahu
R Sahu

Reputation: 206737

When in doubt, simplify.

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

timeline.insert(std::make_pair(key, value));

Upvotes: 5

Related Questions