简体   繁体   中英

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. 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). 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. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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