Linux Map中的两个键值可以相同吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10844702/
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-06 06:36:53  来源:igfitidea点击:

Can two Key Values be same in a Map

c++linuxbooststlmap

提问by payyans4u

I have defined a Map

我已经定义了一个地图

boost::unordered_map<"std::string,std::string">m_mapABC ;

And I Store values in it Like m_mapABC[strValue1]=strValue2;

我将值存储在其中像 m_mapABC[strValue1]=strValue2;

And Assume that i store 10 entries to the map.In that case can the same Key Value be used to store 10 different Values..or will it be over written every time...I guess it would.
In that case using std::pairwould help i guess.

并假设我将 10 个条目存储到地图中。在这种情况下,可以使用相同的键值来存储 10 个不同的值......或者每次都会被覆盖......我想会的。
在那种情况下,使用 std::pair会帮助我猜。

std::map<"std::string, std::pair<"std::string", bool>>myMap2

std::paircan have 2 Key Values Equal(I guess I am Right)...What will be the bool value in each case,will it be TRUE in the first case and FALSE the second time or vice-versa?.

std::pair可以有 2 个相等的键值(我想我是对的)......每种情况下的 bool 值是多少,在第一种情况下为 TRUE,第二次为 FALSE,反之亦然?。

I also heard about std::tupleor boost::tuplewhere a single Key can be used to Store Different Values.

我还听说过std::tuple或者boost::tuple可以使用单个键来存储不同的值。

I am not very clear about how to iterate through them...i need help

我不太清楚如何遍历它们......我需要帮助

采纳答案by nhahtdh

You may want multimapinstead of map.

你可能想要multimap代替map.

回答by Jerry Coffin

If you want to associate more than one value with a single key, use std::multimap(or std::unordered_multimap) instead of std::map.

如果要将多个值与单个键关联,请使用std::multimap(或std::unordered_multimap) 而不是std::map

In some cases, it can make sense to have a std::map<key_type, std::vector<mapped_type> >instead (personally, I frequently find this preferable).

在某些情况下,有一个std::map<key_type, std::vector<mapped_type> >替代是有意义的(就我个人而言,我经常发现这更可取)。

回答by Pablo

If you want to store multiple items with the same key, you should use a multimap(also applies to unordered_variants).

如果要使用相同的键存储多个项目,则应使用 a multimap(也适用于unordered_变体)。

The following should work:

以下应该工作:

std::multimap<std::string,int> mm;
for( int i = 0; i != 10; ++i )
  mm.insert(make_pair("hello world"), i);

And your multimap should contain ten entries with key "hello world" and 10 different values.

并且您的多重映射应该包含十个带有键“hello world”和 10 个不同值的条目。