C ++使用for循环通过Vector进行迭代 [英] C++ Iterate through Vector using for loop

查看:861
本文介绍了C ++使用for循环通过Vector进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是C ++语言的新手。我已经开始使用向量,并注意到,在所有的代码,我看到迭代思考一个向量通过索引,for循环的第一个参数总是基于向量的东西。在Java中我可以用ArrayList做这样的事情:

So I am new to the C++ language. I have been starting to use vectors, and have noticed that in all of the code I see to iterate thought a vector via indices, the first parameter of the for loop is always something based on the vector. In Java I might do something like this with an ArrayList:

for(int i=0; i < vector.size(); i++){
   vector[i].doSomething();
}

有什么原因我在C ++中没有看到这个?是不好的做法吗?

Is there any reason I don't see this in C++? Is it bad practice?

推荐答案


有什么原因我看不到在C ++?这是不好的做法吗?

否。这不是一个坏的做法,但它会让你的代码有一些灵活性

No. It is not a bad practice but it renders your code certain flexibility.

通常,Pre-C ++ 11的代码迭代容器元素使用迭代器,如:

Usually, Pre-C++11 the code for iterating over container elements uses Iterators, something like:

std::vector<int>::iterator it = vector.begin();

这是因为它使代码更灵活。

所有标准库容器支持和提供迭代器,并且如果在以后的开发阶段需要切换另一个容器,则此代码不需要更改。

This is because it makes the code more flexible.
All standard library containers support and provide iterators and given that if at a later point of development you need to switch another container then this code does not need to be changed.

注意:编写代码,与每个可能的标准库容器一起工作并不容易,因为它看起来似乎是。

Note: Writing code which works with every possible Standard library container is not as easily possible as it might seemingly seem to be.

这篇关于C ++使用for循环通过Vector进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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