问题描述
我是 C++ 语言的新手.我已经开始使用向量,并注意到在我看到的所有通过索引迭代向量的代码中,for
循环的第一个参数总是基于向量的东西.在 Java 中,我可能会用 ArrayList 做这样的事情:
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();
}
有什么原因我在 C++ 中看不到这个吗?这是不好的做法吗?
Is there a reason I don't see this in C++? Is it bad practice?
推荐答案
有什么原因我在 C++ 中看不到这个吗?这是不好的做法吗?
没有.这不是一个坏习惯,但以下方法使您的代码具有一定的灵活性.
No. It is not a bad practice, but the following approach renders your code certain flexibility.
通常,在 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. If at a later point of development you need to switch to 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 easy as it might seem to be.
这篇关于使用“for"循环遍历 C++ 向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!