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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With