Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i make an array which is a class object and has a compile time size?

I'm new at this and haven't done much, but I'm really stuck on making a compile-time sized array, which is a class object. And maybe there's a way to save all the information from file, while occupying less of memory? Here's a bit of my code:

#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;
}
like image 617
tendor Avatar asked Nov 29 '25 20:11

tendor


1 Answers

If you don't know the size of an array during compile time, just use 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 behave very similar to arrays, but when using push_back they 'grow' if needed. Notice that they might reserve a little more memory than is necessary so they don't have to grow every time you call push_back. To free this reserved memory you can call shrink_to_fit once afterwards.

If you don't want to use shrink_to_fit you can also make the vector precisely the size you need beforehand using

const int SIZE = count;
std::vector<Beer> allBeers;  
allBeers.reserve(SIZE);
like image 101
Corylus Avatar answered Dec 01 '25 08:12

Corylus