0

I'm trying to implement unordered_map> with using unordered_map::emplace

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int main ()
{
    unordered_map<char,vector<int>>  amap;
    amap.emplace('k',(2,9));
    for(auto i : amap['k']){
    cout << i;
    }

}

I expected output as "99" because I constructed the vector with (2,9). but actual outcome was "000000000" which the emplace constructed vector as (9), 0 being default and 9 as number of ints. I played around little more with other parameter values and realized the emplace only took last value in vector parameter. Why is it?

I can still accomplish the goal by doing

vector<int> v(2,9);
amap.emplace('k',v);

but just wondering why, and save one line of code.

2 Answers2

4
amap.emplace('k',(2,9));

Here (2,9) is just comma separated values. Where everything before , is ignored. So it is like

amap.emplace('k', (9));

gcc even throws a warning

warning: expression result unused [-Wunused-value]

You can use the below

amap.emplace('k', vector<int>(2,9));
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
1

The expression (2,9) is using the built-in comma operator, and the result of that is 9.

You need to provide a proper std::vector object, as in std::vector<int>(2, 9) instead.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621