Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have this 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?

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?

like image 708
whiteSkar Avatar asked Jan 18 '16 06:01

whiteSkar


2 Answers

Simply...

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

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

Sample program at coliru

like image 74
Tony Delroy Avatar answered Oct 14 '22 14:10

Tony Delroy


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.

like image 37
DXsmiley Avatar answered Oct 14 '22 14:10

DXsmiley