end()迭代器上的算术运算 [英] Arithmetic on end() iterator

查看:69
本文介绍了end()迭代器上的算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让A成为std::vector<double>

这是定义明确的吗?

if(!A.empty())
    std::vector<double>::iterator myBack = A.end() - 1;

end迭代器是否仅适用于相等和不相等检查?还是只要保留在容器中就可以执行一些指针算术运算?

Is the end iterator only good for equalities and inequalities checks? Or I can perform some pointer arithmetic as long as I remain in the container?

在我的平台上,此代码有效.我想知道这是否是便携式的.

On my platform this code works. I'm wondering if this is portable.

推荐答案

它完全有效,因为vector::iterator是随机访问迭代器.您可以对其执行算术运算,并且它与平台无关.

It is perfectly valid as vector::iterator is a random access iterator. You can perform arithmetic operations on it and it is not platform dependent.

std::vector<double>::iterator it = A.end();
while (it != A.begin()){
    --it; //this will skip A.end() and loop will break after processing A.front()
    //do something with 'it'
}

但是A.end()指的是理论上的末尾元素,因此它不指向元素,因此不应取消引用.因此,最佳实践是使用反向迭代器而不是递减最终迭代器.

But A.end() refers to theoretical past-the-end element, so it does not point to an element and thus shall not be dereferenced. So best practice is to use reverse iterator instead of decrementing end iterator.

for(std::vector<double>::reverse_iterator it = A.rbegin(); it != A.rend(); ++it) {
    //do something with 'it'
}

这两个循环执行相同的操作,第二个循环是可以理解的,更简洁的方式.

These two loops do the same thing, second is just understandable, cleaner way to do it.

这篇关于end()迭代器上的算术运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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