Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access an index of a map from a pointer

Tags:

c++

c++11

I currently have this

struct test
{
 std::map<int, UINT64> ratio;
}

where pContext is a pointer to test

int group = 1;
auto a = (*pContext).ratio[group]; <---Error

In the above I get the following error

Severity    Code    Description Project File    Line    Suppression State
Error   C2678   binary '[': no operator found which takes a left-hand operand of type 'const std::map<int,UINT64,std::less<int>,std::allocator<std::pair<const int,UINT64>>>' (or there is no acceptable conversion)

Any suggesstion on how I can fix this ?

like image 448
Rajeshwar Avatar asked Sep 05 '25 03:09

Rajeshwar


1 Answers

You seem to have left out important details, but fortunately the error message is sufficient to fill those in. Your pointer is not just "a pointer", it's obviously a const pointer.

The reason this is a problem is due to how operator[] on maps works. That function is non-const (therefore cannot be called on const objects). The reason it's non-const is because it can modify the map: if the key is not found, it will add the key with a default-constructed value and return a reference to that value.

To look up values in your const map, you should use find:

auto it = pContext->ratio.find(group);
if (it != pContext->ratio.end()) {
    std::cout << "Key=" << it->first << " Value=" << it->second << "\n";
}

Actually, you should prefer this for looking up values on any map unless you explicitly want to add missing values or you know for sure that your value is in the map.

And of course, to avoid having to write this grimey stuff manually all the time, just wrap it up into a member function on your struct or similar.

like image 72
paddy Avatar answered Sep 08 '25 05:09

paddy