简体   繁体   English

std :: map一键,两个值

[英]std::map one key, two values

What is the best way to map two values to one key? 将两个值映射到一个键的最佳方法是什么?

ie An item with a value and bool. 即具有值和布尔值的项目。

Tried using: 尝试使用:

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

But that doesn't seem like the correct solution. 但这似乎不是正确的解决方案。 Is there a more elegant way to do this? 有没有更优雅的方式来做到这一点?

That is indeed the correct solution. 这确实是正确的解决方案。 More generally, consider using std::tuple instead of std::pair for a uniform interface regardless of the number of values (as std::pair is obviously restricted to two), or boost::tuple if your compiler is too old to ship with a std:: or std::tr1:: implementation. 更一般地,考虑使用std::tuple而不是std::pair来建立统一接口而不管值的数量(因为std::pair显然限于两个),或者如果你的编译器太旧而不能使用boost::tuple使用std::std::tr1::实现。

Either use std::pair<> as you did, or make a custom struct containing the values you want to store. 或者像你一样使用std::pair<> ,或者创建一个包含你想要存储的值的自定义结构。 I'd do the latter in most cases, as the values then have names more descriptive than first and second . 在大多数情况下我会做后者,因为这些值的名称比firstsecond更具描述性。

通常,我创建一个简单的mapValue结构/类。

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

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