C ++ typedef一个std :: pair,然后使用typedef来声明一个map

问题描述 投票:5回答:3

假设我有这种typedef

typedef std::pair<std::string, uint32_t> MyType;

然后,如果我还想使用MyType创建地图,我该怎么做?

我不想重新键入对中的两种类型:

map<std::string, uint32_t> myMap;

我想要的东西:

map<MyType's first type, MyType's second type> myMap;

有没有办法像使用我的typedef MyType而不是重新键入类型?

c++ dictionary typedef std-pair
3个回答
6
投票

只是...

std::map<MyType::first_type, MyType::second_type> myMap;

http://en.cppreference.com/w/cpp/utility/pair

coliru的示例程序


3
投票

如果您要使用许多不同类型执行此操作,则可以设置别名声明。

template <typename T>
using pair_map = std::map< typename T::first_type, typename T::second_type>;

typedef std::pair<std::string, int> MyType;

pair_map<MyType> my_map;

这至少需要c ++ 11。


0
投票

当您使用一对时,它相当于一个属性。 Pair就像派生数据类型。当您在地图中使用一对时,它将被视为基于您的声明的键或值。但是一对中的第一个和第二个对象不能是地图中的关键和值。您可以分别对两种数据类型使用typedef,并使用快捷方式或上一个答案中提到的。而不是重复写“std ::”,你可以使用命名空间std;谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.