简体   繁体   English

C ++ typedef一个std :: pair,然后使用typedef声明一个映射

[英]C++ typedef a std::pair and then use the typedef to declare a map

Let's say I have this typedef 假设我有这个typedef

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

Then, if I also want to create a map using MyType, how do I do it? 然后,如果我也想使用MyType创建地图,该怎么做?

I don't want to re-type the two types in the pair like: 我不想像这样重新输入一对中的两个类型:

map<std::string, uint32_t> myMap;

I want something like: 我想要类似的东西:

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

Is there a way to do it like that using my typedef MyType instead of re-typing the types? 有没有办法使用我的typedef MyType而不是重新键入类型呢?

Simply... 只是...

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

See http://en.cppreference.com/w/cpp/utility/pair 参见http://en.cppreference.com/w/cpp/utility/pair

Sample program at coliru coliru的样本程序

If you're going to be doing this with a lot of different types, you can set up an alias declaration . 如果要使用许多不同的类型来执行此操作,则可以设置别名声明

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;

This requires at least c++11. 这至少需要c ++ 11。

When you are using a pair it amounts to a single attribute. 当您使用一对时,它相当于一个属性。 Pair is like a derived data type. 配对就像派生的数据类型。 When you are using a pair in map, it is considered as a key or a value based on your declaration. 在映射中使用对时,根据声明将其视为键或值。 But the first and second objects of a pair can't be the key and values in a map. 但是,一对中的第一个和第二个对象不能是映射中的键和值。 You can use typedef for both the data types separately and use the shortcuts or as mentioned in the previous answer. 您可以将typedef分别用于这两种数据类型,并使用快捷方式或如上一个答案中所述。 Instead of writing "std::" repeatedly, You can use using namespace std; 您可以使用命名空间std来代替重复编写“ std ::” Thanks. 谢谢。

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

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