为什么std::remove不能与std::set一起使用?

9
以下代码:
#include <iostream>
#include <set>
#include <algorithm>

std::set<int> s;

int main()
{
    s.insert(1);
    s.insert(2);

    std::remove(s.begin(), s.end(), 1);
}

不能使用gcc 4.7.2编译:

$ LANG=C g++ test.cpp
In file included from /usr/include/c++/4.7/algorithm:63:0,
             from test.cpp:3:
/usr/include/c++/4.7/bits/stl_algo.h: In instantiation of '_FIter std::remove(_FIter, _FIter, const _Tp&) [with _FIter = std::_Rb_tree_const_iterator<int>; _Tp = int]':
test.cpp:12:38:   required from here
/usr/include/c++/4.7/bits/stl_algo.h:1135:13: error: assignment of read-only location '__result.std::_Rb_tree_const_iterator<_Tp>::operator*<int>()'

我查询了fset::iterator的定义, 在gcc实现的文件../c++/4.7/bits/stl_set.h中找到了以下内容:

  // _GLIBCXX_RESOLVE_LIB_DEFECTS                                                                                                                                                             
  // DR 103. set::iterator is required to be modifiable,                                                                                                                                      
  // but this allows modification of keys.                                                                                                                                                    
  typedef typename _Rep_type::const_iterator            iterator;
  typedef typename _Rep_type::const_iterator            const_iterator;
  typedef typename _Rep_type::const_reverse_iterator    reverse_iterator;
  typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator;
  typedef typename _Rep_type::size_type                 size_type;
  typedef typename _Rep_type::difference_type           difference_type;

为什么两个定义都是常量?为什么我的(相当简单的)代码不起作用?

你想做什么?如果要删除单个元素,只需使用erase函数。http://www.cplusplus.com/reference/set/set/erase/ - marcadian
5
名字中有一个诀窍:“remove”并不会删除元素。它会将它们移动到范围的末尾。这在有序容器中是完全不可能的。 - pmr
@marcadian 这只是一个例子,用来说明我的问题。我的实际问题涉及更多的代码,包括 remove_if 和谓词,但问题是一样的。 - ABu
1个回答

18

std::set是有序容器,而std::remove会改变容器中元素的顺序,将应该被移除的元素放在末尾,因此它不能用于那些元素顺序由谓词定义的有序容器。应该使用:

s.erase( 1);

从集合中移除1。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接