Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pair<int, int> as key for map

Tags:

c++

map

std-pair

Based on a previous question, I am trying to create a map using a pair of integers as a key i.e. map<pair<int, int>, int> and I've found information on how to insert:

#include <iostream> #include <map>  using namespace std;  int main () { map<pair<int, int>, int> mymap;  mymap.insert(make_pair(make_pair(1,2), 3)); //edited }    

but I can't seem to access the element! I've tried cout << mymap[(1,2)] << endl; but it shows an error, and I can't find information on how to access the element using the key. Am I doing something wrong?

like image 700
sccs Avatar asked Feb 22 '13 04:02

sccs


People also ask

Can I use pair as key in map?

Do you mean cout << mymap[make_pair(1,2)] << endl; ? (1,2) is non-sensical, at least in this context. You must have an std::pair to be used as your key, and that means following what @andre just commented. Yes!

Can you use a pair as a key in C++?

Using default order So, C++ expects operator< to be defined for the type used for map's keys. Since the operator< is already defined for pairs, we can initialize a std::map with std::pair as the key.

How do you add a pair value to a map?

int a=10,b=20; map < pair < int,int >, int > m; pair < int,int >numbers = make_pair(a,b); int sum=a+b; m[numbers]=sum; Our map will have its key as pairs of numbers. We can access the integer values of pair variable using dot(.) operator.

What is difference between map and pair?

A pair is a single unit with two members. A map has keys and values in it. So you can use pairs to fill up a map, the elements of the pair becoming key and value.


2 Answers

you need a pair as a key cout << mymap[make_pair(1,2)] << endl; What you currently have cout << mymap[(1,2)] << endl; is not the correct syntax.

like image 124
andre Avatar answered Sep 24 '22 06:09

andre


mymap[make_pair(1,2)]

or, with compiler support:

mymap[{1,2}]

like image 29
Louis Brandy Avatar answered Sep 21 '22 06:09

Louis Brandy