我正在撰寫一個程式,其中我將二維向量中的所有元素相加,并找出它們的總和是否為 0。
我在上面的標題和在線編輯器中提到的出現錯誤我收到錯誤 - 分段錯誤
#include <iostream>
#include<vector>
using namespace std;
int main()
{
int num;
cin >> num;
vector<vector<int>> arr;
for (int i = 0; i < num; i )
{
for (int j = 0; j < num; j )
{
cin >> arr[i][j];
}
}
int ans = 0;
for (int i = 0; i < num; i )
{
for (int j = 0; j < num; j )
{
ans = ans arr[i][j];
}
}
if (ans == 0)
cout << "YES";
else
cout << "NO";
return 0;
}
uj5u.com熱心網友回復:
要在向量中顯示某些內容,請使用 .at()
要制作 2d 矢量,您必須組合 2 個矢量:
vector2d.push_back(vector1)
vector2d.push_back(vector2)
現在你有一個二維向量。
在向量 1 或向量 2 上添加您使用 push_back 的內容。
要顯示某些內容或使用二維向量中的值,請使用 vector2d.at().at()
uj5u.com熱心網友回復:
#include <iostream>
#include<vector>
using namespace std;
int main()
{
//User Input
int num {};
cout << "Enter a Number: ";
cin >> num;
//Init Vector
vector <int> V1;
vector <int> V2;
vector<vector<int>> V2D;
//Instead of std:cin we use push back;
for (int i {}; i < num; i ){
V1.push_back(i);
}
for (int j {}; j < num; j ){
V2.push_back(j);
}
//Now we combine the Vectors to a 2D Vector
V2D.push_back(V1);
V2D.push_back(V2);
//Display Vector
//The First Vector is .at(0) and cycles through with each iteration
for(int i {};i<V2D.at(0).size();i ){
cout << V2D.at(0).at(i) << " ";
}
cout << endl;
//The Second Vector is .at(1) and gets Cycled through
for(int j {};j<V2D.at(1).size();j ){
cout << V2D.at(1).at(j) << " ";
}
//The more Vectors you add, the higher the first .at Position gets
//You can mess around with my code and try to implement your idea if you like
//if (ans == 0)
//cout << "YES";
//else
//cout << "NO";
return 0;
}
您不必總共使用 3 個向量,但我發現這樣解釋更容易。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489217.html
上一篇:通過使用宏防止ThisWorkbook中的隱藏作業表可見并從另一個作業簿運行
下一篇:我無法在我的apk版本中顯示影像