C++ 如何插入 std::map?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4375180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:15:44  来源:igfitidea点击:

How to insert into std::map?

c++stl

提问by B?ови?

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

是否有 std 迭代器可用于使用 std 算法(例如 std::copy)将元素插入到 std::map 中?

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.

我需要一个容器来将一个对象链接到一个字符串,并且我考虑过使用 std::map。有没有更好的容器?忘了说 - 项目需要排序。

回答by CashCow

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

我认为 OP 正在寻找的是 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.

输入类型必须是您的地图采用的对类型,否则您的算法将需要使用函数/函子进行 std::transform 才能将输入类型转换为这样的 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).

inserter 实际上不是迭代器,而是一个生成迭代器的模板化函数(std::insert_iterator,它是一个模板化类型,但该类型在函数调用中自动解析)。

回答by Prasoon Saurav

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

为了插入std::map你需要使用std::make_pair().

For example:

例如:

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

Try something similar. :)

尝试类似的东西。:)

回答by Karl Knechtel

Yes, std::copycan insert several elements into a map, if you use a std::insert_iteratoras the OutputIterator (use the helper function std::inserterto 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::transformto produce a sequence of key-value pairs.

是的,std::copy可以将多个元素插入到一个映射中,如果您使用 astd::insert_iterator作为 OutputIterator(使用辅助函数std::inserter创建这些;这样,可以推断模板类型)。std::map 的“元素”是键值对,您可以使用 来创建std::make_pair,如 Prasoon 所示。(实际类型是std::pair<Key, Value>; 再次,辅助函数允许模板类型推导。)如果您有一个序列中的键和另一个序列中的值,您应该能够使用std::transform生成一系列键值对。