C++在临时类中创建数组

C++ creating an array in a temporary class

本文关键字:创建 数组 C++      更新时间:2023-10-16

新手问题!我已经启动了一个小项目,将整数值从文件加载到数组中。(数组需要随机访问,这就是为什么我选择了数组而不是矢量。)

为了从文件中加载数据值,我创建了一个加载/保存类。load函数读取文件的第一行,该行为我们提供了数组所需的条目总数,然后它将用该文件中的其余值填充数组。

这个加载对象只是临时创建的,我想把数据交给程序,然后删除对象。

实现这一目标的最佳方式是什么?我应该在main()中创建数组并向加载对象传递一个引用吗?在这种情况下,我如何创建数组,以便根据需要加载的数据量重新调整其大小。。?

这是加载/保存类:

class FileIOClass {
public:
FileIOClass();
int ReadFile(char*);
private:
};

这是类的cpp代码:

FileIOClass::FileIOClass() {
}
int FileIOClass::ReadFile(char* file_name) {
string line;
ifstream file;
file.open(file_name, ios::in);
cout << "Loading data...n";
int num_x, num_y, array_size;
bool machine_header = false;
if (file.is_open()) {
while(getline(file, line)) {
if (line.size() && machine_header == false) {
// Load machine header information
file >> num_x; 
file >> num_y; 
file >> array_size;
machine_header = true; // machine header has now been read, set this to true.
}
else {
// this is where i want to load the data from the file into an array.
// the size of the array should be equal to the value in array_size.
}
}
cout << "Loading complete!n";
}
else {cout<<"File did not open!n";}
file.close();
return 0;
}

这是迄今为止的主要.cpp:

int main(int argc, char** argv)
{
FileIOClass data_in;
data_in.ReadFile(argv[1]);
return 0;
}

还有其他几个类将处理数组中包含的数据。

我敢打赌,这段代码中有很多奇怪的新手错误——请随时指出,最好现在就学习这些东西。

谢谢大家!

伊恩。

这样的东西可能很好:

vector<int> myVector(array_size);
for(int i=0; file && i<array_size; i++) {
file >> myVector[i];
}

只要您已经决定使用类来读取文件,那么在类中存储数据似乎是合理的。向该类添加一个成员以存储数据:

class FileIOClass {
public:
FileIOClass();
int ReadFile(char*);
unsigned int operator [](int i) const    {return m_data[i];}
int size(void) { return m_data.size(); }
private:
std::vector<int> m_data;
};

并在ReadFile方法中将数据插入该成员:

while(getline(file, line)) {
int pos = 0;
if (line.size() && machine_header == false) {
// Load machine header information
file >> num_x; 
file >> num_y; 
file >> array_size;
m_data.resize(array_size);
machine_header = true; // machine header has now been read, set this to true.
}
else {
file >> m_data[pos++];
// this is where i want to load the data from the file into an array.
// the size of the array should be equal to the value in array_size.
}
}

注意,我重载了[]运算符,所以你可以像这样使用你的类:

int main(int argc, char** argv)
{
FileIOClass data_in;
data_in.ReadFile(argv[1]);
if (data_in.size() >= 1)
cout << data_in[0];
return 0;
}

数组需要随机访问,这就是我选择数组而不是向量的原因。

C++向量允许有效的随机访问(它们是隐藏在引擎盖下的数组)。使用std::vector,除非您已经对代码进行了分析,并发现它们对您正在做的工作效率低下。