C++在临时类中创建数组
C++ creating an array in a temporary class
新手问题!我已经启动了一个小项目,将整数值从文件加载到数组中。(数组需要随机访问,这就是为什么我选择了数组而不是矢量。)
为了从文件中加载数据值,我创建了一个加载/保存类。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,除非您已经对代码进行了分析,并发现它们对您正在做的工作效率低下。
相关文章:
- 在将 new 与指针一起使用时,创建数组的指定长度
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 合并排序不排序自创建数组类 c++
- 基于参数创建数组
- 使用new创建数组而不声明大小
- c++用输入数据创建数组
- 从类 c++ 动态创建数组
- 如何使用 void 函数从类创建数组
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何在不知道Arduino中知道其大小的情况下创建数组和存储值
- 使用动态分配创建数组并将元素插入其中
- 是否可以使用C 函数中的const int参数创建数组
- 如何在C++函数中创建数组
- 使用 ::std::vector 创建数组
- 在编译时以增量方式创建数组
- Numpy C API - 使用 PyArray_Descr 创建数组会导致段错误
- 为什么当我尝试在类中创建数组时"invalid use of non-static data member"我会收到错误?
- 取消引用指针以创建数组的副本
- C++ 在堆上创建数组而不对其进行初始化
- 数组的维度是在创建数组的那一刻确定的,以后不能更改的,这是真的吗?