如何在不知道向量大小的情况下输入向量内部的向量?

How to take input in a vector inside a vector without knowing it's size?

本文关键字:向量 情况下 内部 输入 不知道      更新时间:2023-10-16

所以我有一个问题,要求我输入一个变量列表的列表,其中只给出了列表大小,而没有给出其中变量列表的长度。

输入:

3
1 5 7 2
3 6 2 6 2 4
6 2 3 5 3 

INPUT的第一行是列表列表的大小,后面是大小可变的每个列表的输入。如何在C++中的vector<vector<int>>中接受此输入?

您可以使用std::getline()输入每一行,然后使用istringstreamstd::stoistrings解析为ints

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
vector <vector<int>> DATA;
int main(){
int N;
cin >> N;
string input;
for(int i = 0; i < N; ++i){
getline(cin, input);

istringstream my_stream(input);
vector <int> curr;
int num;
while(my_stream >> num){
curr.push_back(num);
}

DATA.push_back(curr);
cin.ignore();
}
return 0;
}

您可以在std::stringstream的帮助下完成如下操作:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main(void) {
vector<vector<int>> mainVector{};
string tempInput = "";
int number = 0;
int lines = 0;
cout << "Enter the number of lines: ";
cin >> lines;
for (int i = 0; i <= lines; i++) {
// temporary vector
vector<int> tempVector{};
// getting the entire inputted line from the user
getline(cin, tempInput);
// parsing the string into the integer
stringstream ss(tempInput);
// pushing the integer
while (ss >> number)
tempVector.push_back(number);

mainVector.push_back(tempVector);
}
// displaying them back to verify they're successfully stored
for (int i = 0; i <= lines; i++) {
for (size_t j = 0, len = mainVector[i].size(); j < len; j++)
cout << mainVector[i][j] << ' ';
cout << endl;
}
return 0;
}

样本输出:

Enter the number of lines: 3 
1 5 7 2
3 6 2 6 2 4
6 2 3 5 3 
1 5 7 2     // printing the stored vector
3 6 2 6 2 4
6 2 3 5 3
相关文章: