我应该迭代一个向量迭代器还是访问运算符? [英] Should I iterate a vector by iterator or by access operator?

查看:130
本文介绍了我应该迭代一个向量迭代器还是访问运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量声明为

std::vector<int> MyVector;
MyVector.push_back(5);
MyVector.push_back(6);
MyVector.push_back(7);

如何在for循环中使用它?

How do should I use it in a for loop?

通过使用迭代器迭代它。

By iterating it with an iterator?

for (std::vector<int>::iterator it=MyVector.begin(); it!=MyVector.end(); ++it)
{
    std::cout << "Vector element (*it): " << *it << std::endl;
}

还是通过访问迭代器?

for (std::vector<int>::size_type i=0; i<MyVector.size(); i++)
{
    std::cout << "Vector element  (i) : " << MyVector.at(i) << std::endl;
}



在我在互联网上找到的例子中,在所有条件下,他们中的一个是否优于另一个?

In examples I found on internet both of them are used. Is one of them superior to the other under all conditions? If not, when should I prefer one of them over the other?

推荐答案

第一种格式是 more通用 格式,以便迭代标准库容器,因此更常见和直观。如果你需要改变你的容器,那么这个迭代代码保持unimpacted。它将适用于每个标准库容器类型,因此它给你更多的通用代码。

The first format is more generic format for iterating over standard library containers so it is more common and intuitive. If you need to change your container then this iterating code remains unimpacted.It will work for every standard library container type, thus it gives you more generic code.

std :: vector :: at()在每次迭代时调用边界检查边界,因此可能会有点 效果 。这种开销不以第一种格式存在,因为没有进行边界检查。注意,使用 operator [] 也是如此。

注意性能滞后虽然不如你会注意到,除非你在一个巨大的数据上操作。

In second format, std::vector::at() checks for the bounds each time it gets called on every iteration, so it may be a little detrimental to performance. This overhead is not present in the first format as there is no bounds checking involved.Note that same is the case with using operator[].
Note the performance lag though is not as much as you will notice it unless you are operating on a huge data.

这篇关于我应该迭代一个向量迭代器还是访问运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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