6

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
whiteSkar
  • 1,614
  • 2
  • 17
  • 30

3 Answers3

9

Simply...

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

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

Sample program at coliru

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • Ah that's how you use member types on the type.. I tried using dot and arrow operators and didn't work...lol Thank you very much. (will need to wait for 2 min to accept it as answer) – whiteSkar Jan 18 '16 at 06:25
  • But it does depend on `MyType` being a std::pair. If this is a simplified version of the real problem the OP will need to ask another question (and they may well be out of luck). The language doesn't provide a general way to introspect typedefs, one has to rely on the typedef'ed type to provide a mechanism for that. – Martin Bonner supports Monica Jan 18 '16 at 06:25
  • 1
    @MartinBonner My problem is actually the simple pair case. :) – whiteSkar Jan 18 '16 at 06:26
  • 1
    Just for the record, the map will not contain such pairs then! Instead, it will contain `pair`, because the first one (the key) is stored as constant. – Ulrich Eckhardt Jan 18 '16 at 07:01
4

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.

DXsmiley
  • 529
  • 5
  • 17
0

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. Instead of writing "std::" repeatedly, You can use using namespace std; Thanks.

Basant kumar Bhala
  • 174
  • 1
  • 1
  • 11