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

14,956

Solution 1

Simply...

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

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

Sample program at coliru

Solution 2

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.

Share:
14,956
whiteSkar
Author by

whiteSkar

Software Engineer Game Developer C++, C#, Python

Updated on June 04, 2022

Comments

  • whiteSkar
    whiteSkar about 2 years

    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?

  • whiteSkar
    whiteSkar over 8 years
    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)
  • Martin Bonner supports Monica
    Martin Bonner supports Monica over 8 years
    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.
  • whiteSkar
    whiteSkar over 8 years
    @MartinBonner My problem is actually the simple pair case. :)
  • Ulrich Eckhardt
    Ulrich Eckhardt over 8 years
    Just for the record, the map will not contain such pairs then! Instead, it will contain pair<string const,uint32_t>, because the first one (the key) is stored as constant.
  • Martin Bonner supports Monica
    Martin Bonner supports Monica over 8 years
    You can use using namespace std;, but just because you can, doesn't mean it is a good idea.. See stackoverflow.com/questions/1452721/…
  • Basant kumar Bhala
    Basant kumar Bhala over 8 years
    I didn't know that. Thank you for the information @MartinBonner