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,来自 125):

  // _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;

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

4

1 回答 1

18

std::set是有序容器,同时std::remove更改容器中元素的顺序,将应该删除的元素放置到最后,因此它不能与元素顺序由谓词定义的有序容器一起使用。你需要使用:

s.erase( 1);

从集合中删除 1。

于 2013-04-27T22:35:59.563 回答