简体   繁体   中英

What's the fastest way to input data from a txt file and fill a 2D integer vector with it?

I have a vector and a .txt file with numbers. There is a "\\n" at the end of each line. The text file looks like this:

Example:

2 10 529 680 817 865 406 422 827 517 727 667 
4 8 722 682 965 22 341 65 663 687 
6 6 874 416 903 125 942 746 
8 9 424 269 532 807 319 908 603 308 482 
10 10 631 137 557 115 810 294 85 291 997 153 
12 10 249 346 709 115 492 440 713 132 959 723 
14 9 53 270 996 424 239 480 919 867 660 
16 10 634 463 487 197 23 159 147 393 38 926 

I need a really fast way to input the data and fill the vector with it, as I am participating in a competition. The vector after filling it would look like this:

vector<vector<int> > students{
{2, 10, 529, 680, 817, 865, 406, 422, 827, 517, 727, 667 }, 
{4, 8, 722, 682, 965, 22, 341, 65, 663, 687 }, 
{6, 6, 874, 416, 903, 125, 942, 746 }, 
{8, 9, 424, 269, 532, 807, 319, 908, 603, 308, 482 }, 
{10, 10, 631, 137, 557, 115, 810, 294, 85, 291, 997, 153}, 
{12, 10, 249, 346, 709, 115, 492, 440, 713, 132, 959, 723 }, 
{14, 9, 53, 270, 996, 424, 239, 480, 919, 867, 660 }, 
{16, 10, 634, 463, 487, 197, 23, 159, 147, 393, 38, 926}
 };

I have tried using mmap but with no success... Thanks in advance.

PS: I am a rookie so please so some understanding if I don't get what you say.

Edit: This is the code I'm using right now:


for (i = 0; i < numOfStuds; i++)
{
   fscanf(input, "%d %d ", &grade, &univs);
   students[i].push_back(grade);
   backup.push_back(grade);
   students[i].push_back(univs);
   for (j = 0; j < univs; j++)
   {
      fscanf(input, "%d ", &temp);
      students[i].push_back(temp);
   }

}

You can simply read every line and assign to a temporary row. Then assign the row array to your students matrice. Here is my approach:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{

    ifstream file;
    file.open("/home/cayirova/Documents/example.txt",ios_base::app);
    string lines;
    vector<vector<int> > students;
    while (getline(file,lines)) {

        string element = "";   
        vector <int> newRow;

        for(int i=0;i<lines.length();i++)
        {
            if(!isspace(lines[i]))
            {
                element += lines[i];
            }
            if(isspace(lines[i]))
            {
               int assigned_element = stoi(element);
               newRow.push_back(assigned_element);
               element = "";
            }

        }

        students.push_back(newRow);

    }

    for(int i=0; i<8;i++)
    {
        for(int j=0;j<students[i].size();j++)
        {
            cout<<students[i][j]<<" ";
        }

        cout<<endl;
    }

    return 0;

}

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