简体   繁体   English

可以std :: map键地址的值是多少?

[英]May std::map key address number of values?

It may be a little bit stupid question, but assuming the std::map defined as follows: 这可能是一个有点愚蠢的问题,但假设std::map定义如下:

 std::map<int, int> m;

Is there any way to have more than one value stored and be accessible for a single key ? 有没有办法存储多个值并且可以访问单个key

Motivation of asking: 询问的动机:

std::map has methods like count() and equal_range() that get a key as parameters, that kind of give a sense that there is more than one value may be specified by a single key. std::map有像count()equal_range()这样的方法,它们获取一个键作为参数,这种方法equal_range()单个键可以指定多个值。

Those methods exist so as to provide a common interface with other associative containers that do allow multiple values per key (such as std::multimap which is exactly what you're looking for). 存在这些方法以便提供与其他关联容器的公共接口 ,这些容器允许每个键有多个值(例如std::multimap ,这正是您正在寻找的)。

This makes implementing algorithms generically (ie with templates) much easier than it would otherwise be, and nothing of value is lost by designing it this way. 这使得一般地(即使用模板)实现算法比其他方式更容易实现,并且通过这种方式设计没有任何有价值的东西。

It's true that, in the case of std::map , count() can only give you zero or one (unless you're using transparent keys, which are a whole other kettle of fish). 确实,在std::map的情况下, count()只能给你零或一(除非你使用透明键,这是一个完整的其他水壶)。

C++20 will introduce std::map::contains() , which is more or less a check that count() == 1 — this seems to have been intended to address concerns that the function count() is kind of a weird thing to have for a std::map specifically. C ++ 20将引入std::map::contains() ,它或多或少是一个count() == 1的检查 - 这似乎是为了解决函数count()是一种类型的问题。特别是std::map奇怪之处。

Is there any way to have more than one value stored and be accessible for a single key ? 有没有办法存储多个值并且可以访问单个key

Not with std::map , these objects store only one value per key, but std::multimap can store a variable number of values per key. 不使用std::map ,这些对象每个键只存储一个值,但std::multimap可以为每个键存储可变数量的值。

Similarities between both types (eg std::map::count , std::multimap::count ) are due to establishing similar interfaces between STL containers. 两种类型之间的相似性(例如std::map::countstd::multimap::count )是由于在STL容器之间建立类似的接口。

No. std::map is designed to have one value per key. 编号std::map设计为每个键有一个值。 If you want multiple values for one key, you should use std::multimap . 如果您想要一个键的多个值,则应使用std::multimap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM