jeudi 26 juillet 2018

How to use map emplace_hint with non-POD map value?

I have the following class:

class SomeVal
{
  public:
    SomeVal(int _x, int _y) : x(_x), y(_y) {}

    int x;
    int y;
}

Assuming it's being used in the following map:

std::map<double, SomeVal> my_map;

When trying to use emplace_hint to insert an element into it as shown below, I get the no matching function call error message.

Code using emplace_hint:

void func_add_key_to_map()
{

    std::map<double, SomeVal> my_map;

    double key = 123.4;
    int x = 100;
    int y = 2000;

    auto it = my_map.lower_bound(key);

    if (it == my_map.end()) {
        my_map.emplace_hint(it, key, x, y);
    }
}

I also tried:

my_map.emplace(it,
             std::piecewise_construct,
             std::forward_as_tuple(key),
             std::forward_as_tuple(x, y));

and a few other variations. I think I'm understanding emplace_hint wrong. Any suggestions?

Aucun commentaire:

Enregistrer un commentaire