c++ - 为什么 std::remove 采用 const 版本的迭代器?

标签 c++ visual-studio c++11 visual-studio-2013

<分区>

我正在使用 Visual Studio 2013 编译非常简单的代码:

std::set<int> a{ 1, 2, 3 };
std::remove(a.begin(), a.end(), 3);

我希望这不会出错,但我很惊讶。错误发出:

Error   1   error C3892: '_Next' : you cannot assign to a variable that is const    c:\program files (x86)\microsoft visual studio 12.0\vc\include\algorithm

怎么会这样? a 是非常量 std::set。 std::remove() 移动它的元素并且看起来完全合法。

在 VS 2008 中,下面类似的代码编译没有错误:

std::set<int> a;
std::remove(a.begin(), a.end(), 3);

最佳答案

集合是非常量但 set::begin()set::end() 返回一个 const_iterator。可以看出on cppreference .

我相信这是为了避免“局外人”能够交换元素,因为 set 的不变量之一是所有元素都已排序(这正是 std::remove 所做的,它移动元素周围,​​以便您可以在之后对其调用删除,请参阅 erase-remove idiom )

如果你想删除一个元素使用erase成员函数。

关于c++ - 为什么 std::remove 采用 const 版本的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30241347/

相关文章:

visual-studio - 如何使用 .PublishSettings 文件仅将 dist 文件夹部署到 azure 网站

c++ - 将不相关类型的对象重新解释为空类是否是未定义行为

c++ - 运算符上的右值引用模板参数推导

c++ - 如何在 Windows 中锁定文件?

c++ - 尝试分配输出以查看指针和引用输出时,未命名类型错误

c# - 如何在 winform datagridview 中添加数组数据?

vba - 设备字体 cpi 选项仅显示在 Crystal 报表字体属性中

c++ - 使用 MSVC 编译的多线程应用程序在运行时失败

c++ - 未定义的类型特征引用

c++ - vector 无法初始化