我如何制作一个数组,它是一个类对象并具有编译时间大小?

ten*_*dor 2 c++ memory arrays class compile-time

我是新手,并没有做太多,但我真的坚持制作一个编译时大小的数组,它是一个类对象。也许有一种方法可以保存文件中的所有信息,同时占用更少的内存?这是我的一些代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Beer
{
public:
    string name;
    string rating;
    string country;
    string alc;
    string type;
};

int main()   //Function uses ''bytes of stack/exceeds analyze:stacksize '16384'. 
             //Consider moving some data to heap
{
    ifstream file("beer.txt");

    if (!file.good())
    {
        cout << "Error. File was not found." << endl;
        exit(EXIT_FAILURE);
    }
    else
    {
        int count;
        string line;
        ifstream file("beer.txt");
        int count = 0;
        for (int i = 0; !file.eof(); i++)
        {
            getline(file, line);
            count++;
        }

        const int SIZE = count;  //<- this is the place i'm struggling with

        Beer allBeers[SIZE];     //expression must have a constant value
        Beer currentBeer;  

        for (int i = 0; !file.eof(); i++)
        {
            getline(file, currentBeer.name, '\t');
            getline(file, currentBeer.rating, '\t');
            getline(file, currentBeer.country, '\t');
            getline(file, currentBeer.alc, '\t');
            getline(file, currentBeer.type, '\n');

            allBeers[i] = currentBeer;
        }


    }
    file.close();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*lus 5

如果您在编译时不知道数组的大小,只需使用std::vector

#include <vector>

// ...

// const int SIZE = count;  // you don't need this anymore
std::vector<Beer> allBeers;     

// ...

allBeers.push_back(currentBeer); // to append it to your 'array'
Run Code Online (Sandbox Code Playgroud)

vectors 的行为与数组非常相似,但在使用时push_back它们会根据需要“增长”。请注意,它们可能会保留比所需更多的内存,因此每次调用push_back. 要释放此保留的内存,您可以shrink_to_fit在之后调用一次。

如果您不想使用,shrink_to_fit您也可以vector预先使用您需要的精确尺寸

const int SIZE = count;
std::vector<Beer> allBeers;  
allBeers.reserve(SIZE);
Run Code Online (Sandbox Code Playgroud)