lundi 2 mai 2016

Pros/Cons of different types of C++ for-loops?

C++ is very flexible, and I want to understand for-loop operations more deeply. I'm hoping for a good comparison of each implementation and what is better/faster/more efficient. Additionally, it would be a perk to learn some other way of implementing a for-loop - and not necessarily something in the STL.

How do these other for-loops (not the 'traditional') work differently/better?

What are the limitations of the other 'non-traditional' for-loops?

Example 1) Traditional for-loop is:

for(int i=0;i<SIZE;i++){
    //do something for each iteration;
}

Example 2) Now lets say I have a vector of scores.

vector<int> scores = {77,91,100,88,85,68,95};

for (auto it = scores.begin(); it != scores.end(); ++it){
    //do something for each iteration;
}

Example 3) Same scores vector, different loop.

for (auto& x: scores) //do something for each iteration;

I'm particularly interested in example 3, because it is so simple, I'm not sure what it's actually doing, yet functionally is the same as the other two.

Aucun commentaire:

Enregistrer un commentaire