Search code examples
c++for-loopnested-loopsstdvectornested-for-loop

C++: how can I simplify this nested for loop using a range-based for?


Consider the following C++ code snippet, which works as intended. It uses two nested for loops to iterate over an array of vector<int>:

#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";
}

Is it possible to replace the outer for loop with a range-based for loop to make the code simpler? If so, how?

If this change would add complexity instead of reducing it, I'd appreciate an explanation of why a range-based for wouldn’t be beneficial here. Thanks in advance!


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.