c++for-loopnested-loopsstdvectornested-for-loop

C++: nested Ranged For Loops for iterating through vectors of vectors


Consider the following code snippet, taken for a program that works fine.

As you can see, It uses 2 nested for loops to iterate through a vector of vectors:

#define VERTEXES 10

vector<int> adjacency_list[VERTEXES];

for ( int index = 0; index < VERTEXES; index++ ){
    cout << "List[" << index << "]: ";
    for (auto element : adjacency_list[index])
        cout << element << ", ";
    cout << ".\n";
}

Could the first for be replaced by a ranged for too, in order to make the code simpler? If so, how?

If it makes the code more complex I'm not interested, thank you. But, in this case, an explanation of why it cannot make the code simpler is welcome!


Solution

  • Could the first for be replaced by a ranged for too, in order to make the code simpler? If so, how?

    Yes

    for (auto& edge : adjacency_list){
        // cout << "List[" << index << "]: ";
        for (auto element : edge)
            cout << element << ", ";
        cout << ".\n";
    }
    

    Does it make the code simpler? That's up to you to decide, seeing as you are now missing the index of each edge. IMO, it is simpler/less code, therefore less thinking to comprehend.