[英]C++ const_iterator to iterator for forward_list
As per this question , and assuming I have a mutable reference to the container itself , the constness of an iterator can be safely removed using: 根据这个问题,并假设我对容器本身有一个可变引用,则可以使用以下方法安全地删除迭代器的常量性:
foo::const_iterator cit = ... ;
foo::iterator it = c.erase( cit, cit );
However, this doesn't seem to work for forward_list
's equivalent, erase_after
, as per this code::但是,根据此代码,这似乎不适用于forward_list
的等价物erase_after
:
#include <iostream>
#include <forward_list>
typedef std::forward_list<int>::const_iterator CIT;
typedef std::forward_list<int>::iterator IT;
int main()
{
std::forward_list<int> m{1, 2, 3};
CIT cit = m.begin();
IT it = m.erase_after(cit, cit); // Segmentation fault!
std::cout << *it;
}
So is there any way to remove the constness of a const iterator for this class?那么有没有办法删除这个类的const迭代器的constness? Preferably not by iteration!最好不是通过迭代!
You have a segmentation fault because you're violating the precondition of erase_after()
, which states that the range (first, last)
passed to您有一个分段错误,因为您违反了erase_after()
的前提条件,该前提条件指出范围(first, last)
传递给
iterator erase_after(const_iterator first, const_iterator last);
should be a valid range.应该是一个有效的范围。 Note that this is ()
-type of range, not [)
, so both ends are excluded.请注意,这是()
- 范围的类型,而不是[)
,因此两端都被排除在外。 That's why (cit, cit)
is not a valid range for erase_after
.这就是为什么(cit, cit)
不是erase_after
的有效范围的原因。
GCC with -D_GLIBCXX_DEBUG
complains :带有-D_GLIBCXX_DEBUG
GCC抱怨:
Error: function requires a valid iterator range
(__pos, __last)
,__pos
shall be before and not equal to__last
.错误:函数需要一个有效的迭代器范围(__pos, __last)
,__pos
应在__pos
之前且不等于__last
。
although I think it's tricky and STL should provide a normal way to do that, there is also a solution by insert_after
, because:虽然我认为这很棘手并且 STL 应该提供一种正常的方法来做到这一点,但insert_after
也有一个解决方案,因为:
iterator insert_after(const_iterator position, size_type n, const T& x);
Preconditions: position is
before_begin()
or is a dereferenceable iterator in the range[begin(), end())
.前提条件:位置是before_begin()
或者是[begin(), end())
范围内的可解引用迭代器。Effects: Inserts
n
copies ofx
after position.效果:在位置后插入x
n
副本。Returns: An iterator pointing to the last inserted copy of
x
or position ifn == 0
.返回: 如果n == 0
则指向x
或位置的最后插入副本的迭代器。
it returns pos
itself, if n == 0
.它返回pos
本身,如果n == 0
。
if you don't want to create a temporary object of T
, you can use:如果您不想创建T
的临时对象,可以使用:
template<class InputIterator>
iterator insert_after(const_iterator position, InputIterator first, InputIterator last);
or或者
iterator insert_after(const_iterator position, initializer_list<T> il);
and provide an empty sequence or initializer list.并提供一个空的序列或初始化列表。
By iteration you can do it like:通过迭代,您可以这样做:
IT it (m.begin());
for ( CIT cit = m.begin(); cit != m.end(); ++cit )
{
std::advance (it, std::distance<CIT>(it, cit ) );
// do changes on it
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.