lebed2045
lebed2045

Reputation: 468

for loop with auto type over vector of vectors

In the new versions of c++ it's very convenient to use auto as type and range base for loops to do

// instead of
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
}
// to do
for (auto vi: v) {
}

How can I use it for vector<vector<int>>? When I try

for (const auto& vi: vvi) {

}

compilers complains: declaration of variable 'vi' with deduced type 'const auto' requires an initializer.

update: turned out everything works perfectly, I just made a silly typo and put '&' after a variable name instead of a type for (const auto vi&: vvi); I used & to avoid creation of new variable every iteration of the loop.

Upvotes: 1

Views: 1680

Answers (1)

Jarod42
Jarod42

Reputation: 218268

You might use 2 for range:

for (const auto& inner: vvi) { // auto is std::vector<int>
    for (auto e: inner) { // auto is int
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

Upvotes: 4

Related Questions