如何制作一个作为类对象并具有编译时大小的数组?

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

本文关键字:编译 数组 对象 何制作 一个      更新时间:2023-10-16

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

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

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

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

如果您不想使用shrink_to_fit也可以使用事先使用vector精确地制作您需要的尺寸

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

如果您在编译时不知道大小,则应改用std::vector

https://en.cppreference.com/w/cpp/container/vector

#include <vector>

然后

std::vector<Beer> allBeers;

稍后,添加啤酒:

allBeers.push_back(currentBeer);

代码的主要问题在于以下两行:

const int SIZE = count;  //<- this is the place i'm struggling with
Beer allBeers[SIZE];     //expression must have a constant value

现在,尽管SIZE被定义为const但它不是编译时常量!此外,C++中的数组需要编译时常量的维度。(您的const限定符仅表示,一旦初始化,SIZE的值就无法更改。

解决此问题的简单"旧式C++"方法是将allBeers声明为指针,并使用new运算符在运行时创建"数组缓冲区"(当SIZE的实际值已知时(:

const int SIZE = count;  // Don't really need this, now - could just use "count"
Beer* allBeers = new Beer[SIZE]; // You can still use allBeers[i] to access!

但是,在这里,您应该确保在完成数组/缓冲区后执行delete[] allBeers;

更现代的方法是使用std::vector类型,在这种情况下,当对象超出范围时,释放内存会自行处理:

const size_t SIZE = size_t(count);
std::vector<Beer> allBeers(SIZE);

同样,您可以使用allBeers[i]进行访问。

请随时要求进一步澄清和/或解释。