ElevenCents
ElevenCents

Reputation: 73

How do I declare and initialize this map<pair<int, int>, bool>?

While I'm trying to create a map data structure with Key as pair<pair<int, int>, bool and Value as int.

Here's the code:

#include <iostream>
#include <vector>
#include <map>
#include <utility>
using namespace std;

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

struct comp
{
    template<typename T>
    bool operator()(const T &l, const T &r) const
    {
        if (l.first == r.first)
            return l.second > r.second;

        return l.first < r.first;
    }
};

int main()
{
    
    map<pair,bool,comp> mp = 
    {
        {std::make_pair<4,0>,true},
        {std::make_pair<4,1>,true}
    }; //Initializing

    mp.insert(make_pair(3,0),true); //Inserting

    return 0; 
}

The reason I wrote a comp struct with a template is for key ordering.
But, i technically do not need ordering for the problem I'm solving.
So when I tried withunordered_map, it resulted in similar build errors

Upvotes: 0

Views: 855

Answers (1)

asmmo
asmmo

Reputation: 7100

There are several syntactic errors in your example, and an ambiguity due to using namespace std; whilst defining an alias in the global namespace with a colliding name (pair).

Here is your code example after:

#include <map>
#include <utility>

typedef std::pair<int, int> Pair;

struct comp {
  template <typename T> bool operator()(const T &l, const T &r) const {
    if (l.first == r.first)
      return l.second > r.second;

    return l.first < r.first;
  }
};

int main() {

  std::map<Pair, bool, comp> mp = {
      {std::make_pair(4, 0), true},
      {std::make_pair(4, 1), true}}; // Initializing

  mp.insert({std::make_pair(3, 0), true}); // Inserting

}

Upvotes: 5

Related Questions