如何插入std::map?
是否有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为OP正在寻找的是
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:
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 astd::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).为了插入到
std::map
中,您需要使用std::make_pair()
。例如:
尝试类似的事情。 :)
In order to insert into
std::map
you need to usestd::make_pair()
.For example:
Try something similar. :)
是的,如果您使用
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 astd::insert_iterator
as the OutputIterator (use the helper functionstd::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 withstd::make_pair
, as Prasoon illustrates. (The actual type isstd::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 usestd::transform
to produce a sequence of key-value pairs.