gpt4 book ai didi

c++ - 为什么 STL 容器可以使用 const 迭代器插入

转载 作者:太空狗 更新时间:2023-10-29 20:39:10 24 4
gpt4 key购买 nike

为什么STL容器可以使用const_iterator插入?例如,有

iterator std::list::insert (const_iterator position, const value_type& val);

我认为 const_iterator 不允许修改容器。

最佳答案

当一个元素被插入到列表中时,其他元素不会被修改。迭代器仅用于确定插入位置,而不用于修改(= 调用非常量成员函数)任何现有元素。

甚至erase 也可以采用const_iterator。同样,这是因为删除元素也不会修改它。这听起来可能很奇怪,但如果你考虑一下,这就很微不足道了:

void f()
{
std::string const s = "foo";
// the function ends and s is destroyed even though it was constant
}

关于c++ - 为什么 STL 容器可以使用 const 迭代器插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28794827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com