Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase element from set with const key

Unordered set keys are read only, so why in this case I can erase element:

std::unordered_set<std::string> s;
s.emplace("sth");
s.erase("sth");

and in this not:

std::unordered_set<std::string const> s;
const std::string str("sth");
s.emplace(str);
s.erase(str);

If set itself would be const It would make sense but with const keys I don't quite understand that. This assertion fails:

static_assert(!is_reference<_Tp>::value && !is_const<_Tp>::value, "");

Why would somebody who wrote that assertion, check if key is not const?

EDIT:

In fact, the code above compiles fine for std::set. For std::unordered_set, the failure is directly at instantiation. A minimal example to reproduce:

// define a customized hash ... 
int main() { sizeof(std::unordered_set<int const>); }
like image 901
Mateusz Wojtczak Avatar asked Mar 24 '18 18:03

Mateusz Wojtczak


1 Answers

The reason that you cannot erase the element is not because of const-correctness.

It is because you cannot have a container of const things. It is not permitted.

You broke the contract of unordered_set.

The static_assert detected that.

like image 119
Lightness Races in Orbit Avatar answered Sep 26 '22 15:09

Lightness Races in Orbit