使用'for'循环遍历C ++ Vector [英] Iterate through a C++ Vector using a 'for' loop
问题描述
的第一个参数总是基于矢量。在Java中,我可以用一个ArrayList做这样的事情:
$ p $ for(int i = 0; i< vector.size ); i ++){
vector [i] .doSomething();
$ b 是否有一个原因,我没有看到这在C + +?这是不好的做法吗?
解决方案
是否有任何理由我没有看到在C ++?这是不好的做法吗?
没有。这不是一个坏习惯,但是它会使你的代码具有一定的灵活性。
通常,pre-C ++ 11代码用于迭代容器元素使用迭代器,如下所示:
std :: vector< int> :: iterator it = vector.begin();
这是因为它使得代码更加灵活。
所有标准库容器都支持并提供迭代器,并且假如在开发的后期需要切换另一个容器,那么这段代码就不需要改变了。
注意:编写与每个可能的标准库容器一起工作的代码并不像它看起来似的那样容易。
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 though 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();
}
Is there a reason I don't see this in C++? Is it bad practice?
解决方案
Is there any reason I don't see this in C++? Is it bad practice?
No. It is not a bad practice, but it renders your code certain flexibility.
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.
这篇关于使用'for'循环遍历C ++ Vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!