简体   繁体   English

在向量的向量上具有自动类型的 for 循环

[英]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在 c++ 的新版本中,使用 auto 作为循环的类型和范围基础非常方便

// 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>> ?如何将它用于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.编译器抱怨:使用推导类型“const auto”声明变量“vi”需要初始化程序。

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) ;更新:结果一切正常,我只是做了一个愚蠢的错字并在变量名而不是类型之后放了 '&' for (const auto vi&: vvi) I used & to avoid creation of new variable every iteration of the loop.我使用 & 来避免在循环的每次迭代中创建新变量。

You might use 2 for range:您可以使用 2 作为范围:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM