为什么std :: remove不能使用std :: set? [英] Why does std::remove not work with std::set?

查看:490
本文介绍了为什么std :: remove不能使用std :: set?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

#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编译:

does not compile with 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开始):

So I went to the definition of fset::iterator and I've found this in gcc's implementation (file ../c++/4.7/bits/stl_set.h, from 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;

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

Why are both definitions constant? Why does my (pretty simple) code not work?

推荐答案

std :: set 是有序容器,而 std :: remove 更改应放置元素的容器中元素的顺序,因此它不能与有序容器,其中元素顺序由谓词定义。您需要使用:

std::set is ordered container, while std::remove changes order of elements in container placing elements that should be removed to the end, thus it can't be used with ordered containers where elements order is defined by predicate. You need to use:

s.erase( 1);

从集合中删除1。

这篇关于为什么std :: remove不能使用std :: set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆