为什么不修改关联容器的键? [英] Why not modify key of associative container?

查看:127
本文介绍了为什么不修改关联容器的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在关联容器中更改对象的键是一个可怕的想法,但我不知道标准在哪里禁止我这样做。请考虑:

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:

#include <map>
#include <memory>

struct X { int i; };

struct lt
{
  bool operator()( const std::shared_ptr< X >& lhs,
                   const std::shared_ptr< X >& rhs ) const
  {
    return lhs->i < rhs->i;
  }
};

int main()
{
  std::map< std::shared_ptr< X >, int, lt > m;
  auto x = std::make_shared< X >();
  x->i = 1;
  m.insert( std::make_pair( x, 2 ) );

  x->i = 42; // change key wrt the container!
}

我假设上述但我现在正在阅读标准一段时间,我找不到任何实际上使 是非法的。它在哪里?

I assume that the above should be illegal, but I was reading the standard for some time now and I can't find anything that actually makes it illegal. Where is it? Or is it hiding in a future defect report?

推荐答案

这会在程序中注入未定义行为,如果您以某种方式修改值

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.

根据C ++ 11标准的第23.2.4 / 3节([ associative.reqmts]):

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


短语等价键是指通过比较施加的等价关系,而不是
operator == 。也就是说,如果比较
对象<$,则认为两个键 k1 k2 c $ c> comp , comp(k1,k2)== false&& comp(k2,k1)== false 对于
同一容器中的任何两个键 k1 k2 ,调用<$ c $

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.

这篇关于为什么不修改关联容器的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆