28

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?

Community
  • 1
  • 1
sccs
  • 1,123
  • 3
  • 14
  • 27

3 Answers3

18

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.

andre
  • 7,018
  • 4
  • 43
  • 75
12

mymap[make_pair(1,2)]

or, with compiler support:

mymap[{1,2}]

Louis Brandy
  • 19,028
  • 3
  • 38
  • 29
5

Please find the code for the reference:

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


int main()
{

   map<pair<int ,int> ,int > m;
   m.insert({{1, 2}, 100});
   cout << m[{1, 2}];
}
Chandra Shekhar
  • 598
  • 1
  • 7
  • 25