如果输入是:
4
1 6 3 1
6 1 3 1
1 3 1 6
3 1 6 1
我的输出应该是:
18
1 + 6 + 3 + 6 + 1 + 1 = 18
第二个对角线是从右上角开始并向左下角的那个
1
3
3
3
我需要找到严格位于第二对角线以上的元素的总和。
到目前为止,这是我的代码:
int n , sum = 0;
cin >> n;
vector<vector<int>> A(n);
for (auto rows : A)
for (auto elements : rows)
cin >> elements;
for(auto x : A)
sum += A[x] [n - x];
cout << sum;
我是矩阵 vector 的新手。另外,如果你们知道我可以在哪些地方提高我的 vector 技巧,并更好地了解STL vector ,那么您的建议将非常有帮助!
如果您能帮助我,将不胜感激!
谢谢大家的回答!
最佳答案
对于初学者, vector 的定义应类似于
vector<vector<int>> A(n, std::vector<int>( n ) );
这些循环应使用对对象的引用
for (auto &rows : A)
for (auto &elements : rows)
cin >> elements;
要找到总和,可以使用索引变量,例如
long long int sum = 0;
for ( auto n = A.size(); n-- != 0; )
{
for ( std::vector<int>::size_type i = 0; i < n; i++ )
{
sum += A[A.size() - n - 1][i];
}
}
这是一个示范节目
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
int main()
{
size_t n = 0;
std::cout << "Enter the size of a matrix: ";
std::cin >> n;
std::vector<std::vector<int>> v( n, std::vector<int>( n ) );
std::srand( ( unsigned int )std::time( nullptr ) );
for ( auto &row : v )
{
for ( auto &item : row ) item = std::rand() % n;
}
for ( const auto &row : v )
{
for ( const auto &item : row ) std::cout << item << ' ';
std::cout << '\n';
}
long long int sum = 0;
for ( auto n = v.size(); n-- != 0; )
{
for ( std::vector<int>::size_type i = 0; i < n; i++ )
{
sum += v[v.size() - n - 1][i];
}
}
std::cout << "\nThe sum is equal to " << sum << '\n';
return 0;
}
其输出可能看起来像
Enter the size of a matrix: 5
4 4 0 2 0
1 4 4 3 3
3 3 1 0 4
2 0 2 3 2
2 1 3 0 3
The sum is equal to 27
关于c++ - 如何使用vector <vector <int >>找到严格位于矩阵次对角线上的元素之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287087/