C++文件的读取

来源:百度知道 编辑:UC知道 时间:2024/06/24 13:40:58
输入:输入的第一行是一个正整数m,表示测试例个数。接下来几行是m个测试例的数据,每个测试例的数据由两行组成,其中第一行为一个正整数n (n<=500),表示整数序列的长度,第二行给出整数序列,整数之间用一个空格隔开。
例如:文件中的数据是下面这样的,
3
10
9 71 25 64 38 52 5 31 19 45
16
26 35 17 92 53 24 6 57 21 12 34 2 17 86 75 33
20
15 87 32 7 84 35 26 45 78 96 52 22 37 65 9 43 21 3 33 91
而我只有读取整数数列的值,应该怎么读取?我本来想的是用C++的类定义,不知道这样可以吗?
class NUM
{
public:
int text_number;//文件中的测试例个数
int size_of_order;//整数序列的长度
int order[];//整数序列的具体数字
}
那个整数序列的数组大小应该怎么定义? int order[]???

最大的问题就是怎么把文件中数字分别读入到不同的地方?

既然是C++,当然用标准库,当然用vector咯

用 vector<vector<int> > 就可以把整个数据保存了

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

using namespace std;

class NUM
{
private:
vector<vector<int> > datavec;

public:
NUM(ifstream &fin)
{
loadData(fin);
}

public:
void loadData(ifstream &fin);
void chargeEqual();
};

void NUM::loadData(ifstream &fin)
{
int N,M;
fin>>N;
for(int i=0; i<N; ++i)
{
vector<int> vint;
fin>>M;
for(int j=0; j<M; ++j)
{
int num;
fin>>num;
vint.push_back(num);
}
sort(vint.begin(), vint.end());
datavec.push_back(vint);
}
}

void NUM::chargeEqual()
{
vector<vector<int> >::iterator it = datav