container iteration

Suppose you have the following code. The size, and the values used are arbitrary, and only are just exemplary.

Example 1
1
2
3
    std::vector<int> myVector(5, 4); // init the vector with 5 elements, each assigned the value 4
    for(auto i = 0; i < myVector.size(); i++)
        myVector[i] = 33; 


Example 2
1
2
3
    std::vector<int> myVector(5, 4); // init the vector with 5 elements, each assigned the value 4
    for(auto it = myVector.begin(); it != myVector.end(); it++)
        *it = 33;


Lately, I've seen the second example being used more often, however it seems very restrictive. You can find the position of the iterator (within example 2), however its more tedious than the first example. Is there some benefit to using the second method of iteration?
The first example only works with random access containers. The second example works for all containers.
Consider a hypothetical example that you decided to substitute std::vector for std::forward_list.

In this case if you would use the second variant all you need is to change the definition of the object

1
2
3
    std::forward_list<int> myVector(5, 4); // init the vector with 5 elements, each assigned the value 4
    for(auto it = myVector.begin(); it != myVector.end(); it++)
        *it = 33;

Last edited on
Understood, thanks.
The first loop will fail if the size of the vector exceeds INT_MAX, the second loop will work with the vector of any size. (although this can be easily fixed)
Topic archived. No new replies allowed.