問題描述
我是 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++ 向量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!