[英]how to read input properly into a 2D vector, vector<vector<int>> in c++
i need to find the sum of each row using vector < vector > int > >
on a matrix that has n columns, and n rows.我需要在具有 n 列和 n 行的矩阵上使用
vector < vector > int > >
找到每一行的总和。
for example if this is the imput,例如,如果这是输入,
n = 4
1 2 3 4
1 1 1 2
2 2 41 8
3 3 10 2
the output should be output 应该是
10
5
53
18
this is my code so far:到目前为止,这是我的代码:
vector<vector<int>> A;
int n, x;
cin >> n;
for (int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
cin >> x, A[i].emplace_back(x);
for(int i = 0 ; i < n ; ++i)
{
int sum = accumulate(A[i].begin(), A[i].end(), 0);
cout << sum << "\n";
}
Also I don t think that my reading of the matrix is good.我也不认为我对矩阵的阅读很好。
If you could help, it would be very appreciated!如果您能提供帮助,将不胜感激!
Thank you!谢谢!
To read into a 2D vector, you need to read into a 1D vector for each row, and then add that 1D vector to the 2D vector.要读入 2D 向量,您需要为每一行读入 1D 向量,然后将该 1D 向量添加到 2D 向量中。 You could do something like this:
你可以这样做:
for (int i = 0; i < n; ++i)
{
std::vector<int> row;
for(int j = 0; j < n; ++j)
{
cin >> x;
row.push_back(x);
}
A.push_back(row);
}
You could even allocate space for the entire 2D vector, and then read directly into the correct positions, like this:您甚至可以为整个 2D 向量分配空间,然后直接读取到正确的位置,如下所示:
auto A = std::vector<std::vector<int>>(n, std::vector<int>(n, 0));
for (int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
cin >> A[i][j];
You could simplify this even further as the comment suggests正如评论所建议的那样,您可以进一步简化这一点
auto A = std::vector<std::vector<int>>(n, std::vector<int>(n, 0));
for (auto &row : A)
for(auto &element : row)
cin >> element;
Your code to sum up the rows seems reasonable.您总结行的代码似乎是合理的。
int n, x;
cin >> n;
vector<vector<int>> A(n);
for (int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
cin >> x, A[i].push_back(x);
for(int i = 0 ; i < n ; ++i)
{
int sum = accumulate(A[i].begin(), A[i].end(), 0);
cout << sum << "\n";
}
The problem is you are trying to access A[i] when there are no vectors in the vector of vectors问题是当向量的向量中没有向量时,您正在尝试访问 A[i]
vector<vector<int>> A ----> {}
vector<vector<int>> A(4) ----->{{}{}{}{}} // constructor initializes with 4 empty vectors
now you can access A[i] which returns the ith vector object on which you can do a push_back to insert a element现在您可以访问返回第 i 个向量 object 的 A[i],您可以在其上执行 push_back 以插入元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.