c++ - To iterate or to use a counter, that is the question -


Whenever a person starts using STL and has a vector, you usually see:

 vector & lt; Int & gt; Vec; // ... for code ... (vector  :: Iterator iter = vec.begin (); iter! = Vec.end (); ++ iter) {// do stuff} 

Just call me the full vector & lt; Int & gt; :: Iterator is getting sick in syntax. I know that you type typedef vector & lt; Int & gt; :: iterator can vecIterInt , and that is a little better ..

But the question is, what is wrong is ol ':

For
 (int i = 0; i & lt; vec.size (); i ++) {// code} 

When you use the index to run sequential access to the container ( std :: vector or something else) Implementing the random-access requirement on the underlying data structure, when you actually need to Such access does not require algorithms. The requirement of random access is a strong requirement compared to a fairly weak requirement of sequential access . It is a major design error affecting strong requirement without any good reason.

So the correct answer to your question is: use the sequel (iterator) access whenever you can, only when you have to do it exactly.

If your algorithm seriously relies on the random-accessible container, then it becomes the external requirement of the algorithm. In this case, you can use the index without any reservation. However, if it is possible to apply the same algorithm using the etorrers, then staying with only itators is a good practice, i.e. only relying on sequential access.

Of course, the above rule, while true, only makes sense in the code normal to a certain degree if any other part of the code is such a specific So you know to make sure that the data structure you are working with is a std :: vector and always a study :: vector , then Access method now matters Whatever you prefer, use it, however, the sequential access is completely Yapt, then I would like to avoid reaching the index in those situations.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

jquery - SimpleModal Confirm fails to submit form -