Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into std::map?

Tags:

c++

stl

Is there a std iterator I could use to insert elements into std::map using a std algorithm (for example std::copy) ?

I need a container to link one object to a string, and I thought about using std::map. Is there a better container? Forgot to say - items needs to be sorted.

like image 942
BЈовић Avatar asked Dec 07 '10 09:12

BЈовић


People also ask

What does insert return in map?

Return Value: The function returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element with an equivalent key in the map.

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.

Which method do you use to add an element to a map?

set() The set() method adds or updates an entry in a Map object with a specified key and a value.


2 Answers

I think what the OP is looking for is std::inserter(mymap, mymap.end())

so you can do:

std::copy( inp.begin(), inp.end(), std::inserter(mymap, mymap.end()) ); 

The input types must be a pair type that your map takes, otherwise your algorithm would need to be std::transform with a function/functor to convert the input type into such a std::pair.

inserter is not actually an iterator but a templated function that produces an iterator (std::insert_iterator, which is a templated type but the type is automatically resolved in the function call).

like image 69
CashCow Avatar answered Oct 10 '22 20:10

CashCow


In order to insert into std::map you need to use std::make_pair().

For example:

std::map<int,std::string> Map; Map.insert(std::make_pair(5,"Hello")); 

Try something similar. :)

like image 28
Prasoon Saurav Avatar answered Oct 10 '22 20:10

Prasoon Saurav