如何在不修改当前迭代器的情况下获取循环中的下一个/上一个迭代器?我不能使用operator++
或operator--
,因为这会干扰循环的实际迭代。C++迭代器遍历
如果我正在遍历数组索引i
,我可以说A[i+1] = A[i]
而不实际修改i
。我如何做迭代器的等价物?
如何在不修改当前迭代器的情况下获取循环中的下一个/上一个迭代器?我不能使用operator++
或operator--
,因为这会干扰循环的实际迭代。C++迭代器遍历
如果我正在遍历数组索引i
,我可以说A[i+1] = A[i]
而不实际修改i
。我如何做迭代器的等价物?
如果C++ 11,使用std::next()
:
auto it = ...;
auto next_it = std::next(it); // doesn't modify 'it'
如果C++ 03,写自己的std::next()
基于关闭的std::advance()
:
template<class ForwardIt>
ForwardIt next(ForwardIt it,
typename std::iterator_traits<ForwardIt>::difference_type n = 1)
{
std::advance(it, n);
return it;
}
注意,如果你的迭代器是随机访问迭代器,你可以为数组索引做同样的事情。那就是:
auto next_it = it + 1;
mine是一个随机访问(向量),所以假设我想用当前元素替换下一个位置,这将工作吗?它+ 1 = *它; –
@Bijeetchatterjee你的意思是'*(it + 1)= * it;'。 – emlai
否我的意思是(it + 1)= * it; –
'的std :: VECTOR'标记,是'* (it + 1)'有问题? – LogicStuff