繁体   English   中英

从 txt 文件输入数据并用它填充二维整数向量的最快方法是什么?

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

我有一个矢量和一个带有数字的 .txt 文件。 每行末尾都有一个“\\n”。 文本文件如下所示:

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 

我需要一种非常快速的方法来输入数据并用它填充向量,因为我正在参加比赛。 填充后的向量将如下所示:

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

我曾尝试使用 mmap 但没有成功......提前致谢。

PS:我是菜鸟,如果我不明白你的意思,请多多谅解。

编辑:这是我现在使用的代码:


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

}

您可以简单地读取每一行并分配给一个临时行。 然后将行数组分配给您的学生矩阵。 这是我的方法:

#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;

}

暂无
暂无

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

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