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

编程入门 行业动态 更新时间:2024-10-14 04:29:27
本文介绍了为什么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?

本文发布于:2023-11-29 21:20:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   remove   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!