如何插入std::map?

发布于 2024-10-06 17:39:20 字数 132 浏览 0 评论 0原文

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

我需要一个容器将一个对象链接到一个字符串,我考虑使用 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 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

风吹短裙飘 2024-10-13 17:39:20

我认为OP正在寻找的是 std::inserter(mymap, mymap.end())

所以你可以这样做:

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

输入类型必须是你的地图采用的对类型,否则你的算法需要使用函数/函子来将输入类型转换为这样的 std::pair 。

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

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

九公里浅绿 2024-10-13 17:39:20

为了插入到 std::map 中,您需要使用 std::make_pair()

例如:

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

尝试类似的事情。 :)

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

稍尽春風 2024-10-13 17:39:20

是的,如果您使用 std::insert_iterator 作为 OutputIterator(使用辅助函数 std:: inserter 创建这些;这样就可以推断出模板类型)。 std::map 的“元素”是键值对,您可以使用 std::make_pair 创建它们,如 Prasoon 所示。 (实际类型是 std::pair;同样,辅助函数允许模板类型推导。)如果您的键位于一个序列中,而值位于另一个序列中,则应该能够使用 std::transform 生成一系列键值对。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文