我在遍历 vector<vector<?> >
时遇到了一些问题与 for_each功能。
每当我做这样的事情时(其中 matrix
是我的嵌套 vector ):
int size = 0;
for_each(matrix.begin(), matrix.end(), [](vector<int> &vec) {
size += vec.size();
});
然后编译器用 expected primary-expression before '[' token
向我提示错误(有更多相同的错误,但带有 ]
和 &
字符)。我究竟做错了什么? cppreference 上的示例 here与 int
具有相似的语法,那么是什么让它与众不同?
最佳答案
你确定你包括了正确的 header ,using namespace std;
(我更喜欢用 std::
明确地作为前缀,如下所示),并启用 C+ +11 为您的编译器?您还需要捕获 size
。无论如何 - 工作代码:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::vector<int>> matrix = { { 1, 2 }, {3, 4, 5}, {6} };
size_t size = 0;
std::for_each(matrix.begin(), matrix.end(), [&size](std::vector<int> &vec) {
size += vec.size();
});
std::cout << size << '\n';
}
看它运行here
关于评论中的问题:
What if this is surrounded by another for_each loop that's getting each vector individually; what would that look like?
您可以嵌套 for_each
循环如下,但它可能不是您在功能上需要的 - 无法从这样一个模糊的问题中分辨出来:
std::for_each(matrix.begin(), matrix.end(),
[&size, &matrix](std::vector<int>& outer_vec)
{
std::for_each(matrix.begin(), matrix.end(),
[&size](std::vector<int> &vec)
{
size += vec.size();
});
});
关于c++ - 用 for_each 遍历 vector<vector<?>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29618367/