所以我最近開始學習C++,我試圖弄清楚如何訪問一個多維向量或者向量存儲在其中的向量。我看遍了所有,我無法找到我正在尋找什麼。我希望能夠通過打印出來測試多維向量中每個向量的內容。此外,無論何時在每次迭代後嘗試查看矢量的大小,每次迭代都會得到隨機常量。他們看起來像他們可能是記憶位置,但我不確定。多維向量?
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int numofArrays;
int numofQueries;
vector<vector<int>> arr(numofArrays);
cin >> numofArrays;
cin >> numofQueries;
int arrSize;
int number;
vector<int> indArr;
// Outer loop, appends vectors containing ints to a multidimensional vector
for (int i = 0; i < numofArrays; i++) {
cin >> arrSize; // Getting number of elements from user
// Inner loop, gets user inputted values then creates a vector which is added to the multidimensional vector
for (int x = 0; x < arrSize; x++) {
cin >> number;
indArr.push_back(number);
cout << "Last number added to vector: " << number << endl; // Checking to see if correct numbers are being added.
}
arr.push_back(indArr);
cout << "Multidimensional Vector size: " << arr.size() << endl; // Checking size of vector after each iteration
indArr.clear(); // Empties vector for next iteration
}
return 0;
}
由於我很新的C++,我歡迎建設性的批評。
新修代碼:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int numofArrays;
int numofQueries;
cin >> numofArrays;
cin >> numofQueries;
vector<vector<int>> arr(numofArrays);
// Outer loop, appends vectors containing ints to a multidimensional vector
for (int i = 0; i < numofArrays; i++) {
int arrSize;
vector<int>indArr;
cin >> arrSize; // Getting number of elements from user
indArr.resize(arrSize); // Resizing array for next values
// Inner loop, gets user inputted values then creates a vector which is added to the multidimensional vector
for (int x = 0; x < arrSize; x++) {
int number;
cin >> number;
indArr.push_back(number);
cout << "Last number added to vector: " << number << endl; // Checking to see if correct numbers are being added.
}
arr.push_back(indArr);
cout << "Multidimensional Vector size: " << arr.size() << endl; // Checking size of vector after each iteration
}
int test = arr[0][0];
cout << test;
return 0;
}
所有你需要做的是弄清楚如何使用一個向量,因爲「多維向量」只是一個向量。 – juanchopanza
但我之前使用過矢量,它的行爲不像任何矢量。你能解釋我做錯了什麼嗎?爲什麼每當我打印出「cout <<」多維向量大小:「<< arr.size()<< endl; //每次迭代後檢查向量的大小」這一行時,我都會收到一個超過4000000的數字? – King
可能是你的代碼中的一個無聊的東西。 – juanchopanza