开发者

How to insert into std::map?

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 containe开发者_如何学运维r 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.


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


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. :)


Yes, std::copy can insert several elements into a map, if you use a std::insert_iterator as the OutputIterator (use the helper function std::inserter to create these; this way, the template type can be inferred). The "elements" of a std::map are key-value pairs, which you can create with std::make_pair, as Prasoon illustrates. (The actual type is std::pair<Key, Value>; again, the helper function allows for template type deduction.) If you have the keys in one sequence and the values in another, you should be able to use std::transform to produce a sequence of key-value pairs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜