【发布时间】:2020-07-11 18:16:13
【问题描述】:
所以我有一个问题要求我输入一个变量列表列表,我只得到列表大小而不是其中变量列表的长度。
输入:
3
1 5 7 2
3 6 2 6 2 4
6 2 3 5 3
INPUT 的第一行是列表列表的大小,然后是每个大小可变的列表的输入。如何在 C++ 中的 vector<vector<int>> 中获取此输入?
【问题讨论】:
所以我有一个问题要求我输入一个变量列表列表,我只得到列表大小而不是其中变量列表的长度。
输入:
3
1 5 7 2
3 6 2 6 2 4
6 2 3 5 3
INPUT 的第一行是列表列表的大小,然后是每个大小可变的列表的输入。如何在 C++ 中的 vector<vector<int>> 中获取此输入?
【问题讨论】:
您可以使用std::getline() 输入每一行,然后使用istringstream 或std::stoi 将strings 解析为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;
}
【讨论】:
cin.ignore()
vector library。
您可以在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
【讨论】: