Santosh Sahu
Santosh Sahu

Reputation: 2244

unordered_map::insert vs operator []= function giving error

I am inserting records to an unordered map, which results in an error, below is the program:

#include<tr1/unordered_map>
using namespace std;

int main(int argc, char *argv[])
{
    std::tr1::unordered_map<int, int> u1;
    int n;
    cout << "Enter the no. of times" << endl;
    cin >> n;
    for (int i = 0; i<n; i++)
    {
        int no_items;
        cout << "Enter no of items" << endl;
        cin >> no_items;
        for (int j = 0; j<no_items; j++)
        {
            int key, val;
            cout << "key=";
            cin >> key;
            cout << endl << "val=";
            cin >> val;
            u1.insert(std::make_pair<int, int>(key, val)); //Compiler error
                                                           //u1[key]=val; //This line is working instead of insert.
        }
    }
    return 0;
}

u1.insert(std::make_pair<int,int>(key,val)); gives error

  • cannot convert 'key' (type 'int') to type 'int&&'
  • no matching function for call to 'make_pair(int&, int&)'

Wondering how operator [] for inserting records into unordered_map is working and insert() function not.

Upvotes: 1

Views: 245

Answers (3)

SergeyA
SergeyA

Reputation: 62563

I would even recommend doing emplace - to save on creating a temporary. Check out this:

u1.emplace(key, val);

Upvotes: 1

Sam Daniel
Sam Daniel

Reputation: 1902

u1.insert(std::make_pair<int,int>(key,val));

works if g++ is invoked without -std=c++11

but for c++11, we need to give as...

u1.insert(std::make_pair(key,val));

Because earlier versions of make_pair is

template <class T1,class T2>
  pair<T1,T2> make_pair (T1 x, T2 y)
  {
    return ( pair<T1,T2>(x,y) );
  }

but from c++11, the signature is

template <class T1, class T2>
pair<V1,V2> make_pair (T1&& x, T2&& y);

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36463

The 2 arguments for std::make_pair are forwarding references T&&. Just let the compiler do the type deduction instead:

u1.insert(std::make_pair(key,val));

Upvotes: 3

Related Questions