首页 > 解决方案 > 我如何制作一个作为类对象并具有编译时大小的数组?

问题描述

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

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

标签: c++arraysclassmemorycompile-time

解决方案


如果您在编译期间不知道数组的大小,只需使用 a 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'

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

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

const int SIZE = count;
std::vector<Beer> allBeers;  
allBeers.reserve(SIZE);

推荐阅读