如何在不知道向量大小的情况下输入向量内部的向量?
How to take input in a vector inside a vector without knowing it's size?
所以我有一个问题,要求我输入一个变量列表的列表,其中只给出了列表大小,而没有给出其中变量列表的长度。
输入:
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;
}
您可以在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
相关文章:
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 如何在不C++排序的情况下找到给定向量中的第一、第二和第三高值?
- 如何在不复制的情况下将一个向量移动到另一个向量中
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 在无法访问向量的情况下查找迭代器的末尾
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 我怎样才能在不重复的情况下随机迭代向量的每个元素
- 调整向量大小并检索值,这是否正确或在任何情况下都可能导致段错误?
- 如何在不迭代的情况下从string_view向量创建字符串向量?
- 如何在不以不同方式创建每个向量的情况下制作 2-D 向量列表?
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- 是否可以在不指定类型的情况下从 istringstream 转到向量?
- 在不使用递归的情况下求解所有 2D 字符串向量组合?(C++)
- 如何在不复制的情况下将向量向量从类函数传递到功能
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 我可以在不循环访问数组/向量的情况下检查数组/向量中的单词吗?
- 如何在使用和无发现的情况下使用和不使用的字符串向量搜索元素
- 您可以在没有列表或向量的情况下循环访问类对象吗?
- 如何在给定迭代器列表的情况下从向量中删除元素
- 一般情况下,在 cv::Mat 或 cv::Mat 的向量上进行 omp 还原