在C ++中使用包含不同类型键的映射 [英] Have a map with keys consisting of different types in C++
问题描述
我目前在C ++中使用地图,并且有一些int和布尔值的值,尽管其中大部分都是字符串。我知道在Java中我可以这样做:
I currently am using a map in C++ and have a couple of values that are ints and booleans, though the majority of them are strings. I know in Java I could do something like this:
std::map<string, Object*> mapvar;
但是在C ++中有一个 Object
等价物??如果没有,我有什么办法可以正确地让值为 std :: string
, int
或 bool
?
but is there an Object
equivalent in C++?? If not, is there any way I could properly have values being a std::string
, int
, or bool
?
推荐答案
我不知道你可以拥有一个方法 std :: map
,其中可以使用 stdlib
开启多个类型的键。
I don't know of a way you could have a std::map
with keys that can be multiple types using the stdlib
out of the box.
Boost有一个变体
类型,其功能或多或少像您想要的那样。
Boost has a variant
type that functions more or less like what you want.
typedef boost::variant<std::string, int, bool> key_type;
std::map<key_type, Object*> mapvar
此地图只接受在您选择的key_type中定义的键 ,所以你也不能使用 std :: wstring
作为关键字而不显式声明它。这将是在任何
之上使用变体
的优点。后者可能会喜欢吃任何你发送的类型,而前者会给你一个编译时错误。
This map will only accept keys that are defined in your chosen key_type, so you could not also use, say, a std::wstring
as a key without explicitly declaring it. This would be the advantage of using a variant
over any
. The latter might happily eat whatever type you send its way, while the former will give you a compile time error.
如果你打算使用 boost :: variant
作为你的密钥,那么你需要阅读boost文档,并研究构建变体
对象以及是否涉及他们有排序预定义。 std :: map
建立在运算符<
之上(除非您在其他排序函子上模板化)需要确保您的变体
类型的工作定义由库或您自己提供。
If you are going to use a boost::variant
as your key then you need to read the boost documentation and look into what is involved in constructing variant
objects and whether or not they have sorting pre-defined. std::map
is built on operator<
(unless you template it on some other sorting functor) so you'll need to make sure a working definition for your variant
type is provided by either the library or yourself.
-
为什么你想要这样的地图呢?
Why do you want to have such a map in the first place?
这篇关于在C ++中使用包含不同类型键的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!