【问题标题】:Change/update value using std::map const_iterator使用 std::map const_iterator 更改/更新值
【发布时间】:2019-12-02 20:43:44
【问题描述】:

我只是想知道是否可以使用 const_iterator 更改/更新地图的值。

下面是sn-p的代码:

int main()
{
    map <int, int> m;
    m.insert(make_pair(1, 10));

    map <int, int>::const_iterator itr = m.begin(); //The iterator is const_iterator
    itr->second = 30;

    cout << itr->second; //The value to be printed is 30, and not 10.
    return 0;
}

提前感谢您分享您的想法。

【问题讨论】:

  • 您能详细说明为什么您认为这应该是可能的吗? const_iterator这个名字中的“const”怎么理解?
  • 代码无法编译并显示消息“错误:只读对象中成员 'std::pair::second' 的赋值”。很明显,你不能用这段代码来做。您是否要求一种方法来规避这种行为,例如使用const_cast 或类似的东西?

标签: c++ stl stdmap const-iterator


【解决方案1】:

无法通过 const 迭代器更改元素。这是 const 迭代器和非 const 迭代器之间最重要的区别。

std::map::begin 返回一个非常量迭代器(假设对象操作数是非常量),所以一开始就不需要使用常量迭代器。

但是,如果由于某种原因(未在示例中演示)您只能拥有一个 const 迭代器,但可以对容器进行非 const 访问,那么您可以获得一个指向 const 指向的元素的非 const 迭代器迭代器。这可以通过使用以下方法来实现,这看起来像是一个技巧:

map <int, int>::iterator mutable_itr = m.erase(itr, itr);

它不会删除任何内容,因为[itr, itr) 是一个空范围。

【讨论】:

  • 第一印象:哎呀,太可怕了!但我看到了它的聪明之处,它仍然是安全的,因为非常量 m 没有 erase()。
  • @TobySpeight 这也是我的第一印象。我的第二个印象:为什么没有聪明的地方就没有标准函数可以做到这一点?
【解决方案2】:

const 迭代器应该防止用户以任何方式更改/修改值。

【讨论】:

    【解决方案3】:

    我可以使用 const_iterator 更改/更新地图的值吗?

    没有!

    它被称为 const 迭代器是有原因的。如here 所述,const_iterator 是一个指向 const 值的迭代器(如 const T* 指针);取消引用它会返回对常量值 (const T&amp;) 的引用并防止修改引用的值:它强制执行 const-correctness。

    【讨论】:

      【解决方案4】:

      编译器不应允许通过const_iterator 修改map 的内容。线

      itr->second = 30;
      

      应报告为错误。如果您的编译器允许该行,则它不符合标准。也许它允许通过允许标准不兼容行为的标志编译该行。

      使用 g++,我得到以下错误。

      socc.cc: In function ‘int main()’:
      socc.cc:12:19: error: assignment of member ‘std::pair<const int, int>::second’ in read-only object
           itr->second = 30;
      

      【讨论】:

        【解决方案5】:

        const_iterator 的全部点在于它不能用于修改容器。所以没有。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-26
          • 1970-01-01
          • 2018-11-19
          • 1970-01-01
          • 2011-05-30
          • 2017-05-06
          • 2017-01-20
          相关资源
          最近更新 更多