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

时间:2013-12-23 13:35:04

标签: c++ arrays

新手问题!我已经开始了一个小项目,它将文件中的整数值加载到数组中。 (需要随机访问数组,这就是我选择数组而不是向量的原因。)

要从文件中加载数据值,我创建了一个Load / Save类。 load函数读取文件的第一行,它给出了数组需要的条目总数,然后它将用该文件中的其余值填充数组。

此加载对象仅临时创建,我想将数据提供给程序,然后删除该对象。

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

这是加载/保存类:

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

目前为止是main.cpp:

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

    return 0;
}

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

我打赌这段代码中有很多奇怪的新手错误 - 请随时指出它们,现在更好地学习这些东西。

全部谢谢!

伊恩。

3 个答案:

答案 0 :(得分:1)

这样的事可能会很好:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

  

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

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