简体   繁体   English

输入从fstream到2d vector &lt;vector的整数 <int> &gt; C ++

[英]Input integers from fstream to 2d vector< vector<int> > C++

I am trying to use push_back to dynamically add integers from an ifstream to a 2d vector. 我正在尝试使用push_back将ifstream中的整数动态添加到2d向量中。 Basically input will be fed in similar to : 基本上,输入的输入方式类似于:

3
20 3
30 4
40 5 
3
50 6
60 7
70 8

and I want to read the int's by themselves (3,3 ..etc), and then create the 2d vector of the pairs of numbers (the int's by themselves describe how many pairs there will be). 我想自己读取int的值(3,3 ..etc),然后创建数字对的2d向量(int值本身描述将会有多少对)。 Right now I am using getline() and storing the digits in a char, then converting them to int's again, but I feel that this may not be ideal. 现在,我正在使用getline()并将数字存储在char中,然后再次将其转换为int的数字,但是我觉得这可能并不理想。 If anyone has any ideas I would appreciate it. 如果有人有任何想法,我将不胜感激。

Something like (untested): 像(未经测试的):

std::istream_iterator<int> eos;
std::vector<std::vector<int>> matrix;
while(std::getline(str, line))
{
  std::istringstream istr(line);
  std::istream_iterator<int> iin(istr);
  std::vector<int> columns;
  std::back_insert_iterator<vector<int>> back_it(columns);
  std::copy(iin, eos, back_it);
  matrix.push_back(columns);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM