Why not modify key of associative container?

后端 未结 1 1841
终归单人心
终归单人心 2020-12-19 05:38

I know that it\'s a terrible idea to change the key of an object in an associative container, but I wonder where exactly the standard forbids me to do so. Consider:

相关标签:
1条回答
  • 2020-12-19 06:04

    This injects Undefined Behavior in your program if you modify the values in a way that the comparison of any two keys is different after the change according to the comparator you specified.

    Per Paragraph 23.2.4/3 of the C++11 Standard ([associative.reqmts]):

    The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator== on keys. That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false. For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.

    0 讨论(0)
提交回复
热议问题