对于n行,如何获得直到n的整数



我的输入:第一个输入是输入将包含

的行数
5
7 3 29 0
3 4 3 
2 3 4 55 5
2 3
1 2 33 4 5

我的问题是我如何将它们存储在向量的向量…?

. .我的概念

.
.
.
cin>>n;
vector<vector<int>>vec;
while(n--)
{
vector<int>vec2;
for(**Getting input until the line**){
vec2.emplace_back(input);}
vec.emplace_back(vec2)
}

我需要实现获取输入直到行。为此,我想到将输入作为字符串并使用strtok将值存储在矢量vec2中转换成c_string后…但是我想知道是否有什么有效的方法可以解决这个问题。

这是我的建议,YMMV

  1. 将每一行读入字符串
  2. 使用istringstream从字符串中提取整数,变成一个向量。
  3. 字符串处理后,push_back将向量转换为外部向量。
unsigned int rows;  
std::cin >> rows;  
std::string text_row;  
for (unsigned int i = 0U; i < rows; ++i)  
{  
std::getline(cin, text_row);  
std::istringstream numbers_stream(text_row);  
std::vector<int>  row_data;  
int number;  
while (numbers_stream >> number)  
{  
row_data.push_back(number);  
}  
vec.push_back(row_data);  
}  

最新更新