c++ - 我如何制作一个作为类对象并具有编译时大小的数组?
问题描述
我是新手,没有做太多,但我真的坚持制作一个编译时大小的数组,它是一个类对象。也许有一种方法可以保存文件中的所有信息,同时占用更少的内存?这是我的一些代码:
#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;
}
解决方案
如果您在编译期间不知道数组的大小,只需使用 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'
vector
s 的行为与数组非常相似,但在使用时,push_back
如果需要,它们会“增长”。请注意,它们可能会保留比必要更多的内存,因此它们不必在每次调用时都增加push_back
。要释放此保留的内存,您可以shrink_to_fit
在之后调用一次。
如果您不想使用shrink_to_fit
,您也可以vector
预先使用您需要的尺寸
const int SIZE = count;
std::vector<Beer> allBeers;
allBeers.reserve(SIZE);
推荐阅读
- visual-studio-code - 如何在 VS Code 中使用断点调试 Ember 插件
- assembly - 汇编语言命令行
- python - Google Kick Start 2020 C 轮:稳定墙。总是 WA 但找不到问题
- jekyll - 如何在 Jekyll 中将字符串转换为日期?
- python - 使用 pip 安装后在 Anaconda 导航器上找不到包
- react-native - 无法解析模块 multer
- lucene - 当我添加未找到的新文档时,为什么 Lucene 文档顺序会更改(分数)
- python - 使用 python opencv 进行照明标准化
- django - 如何解决此错误“'password_reset' 不是 rest api django 中的注册命名空间”
- javascript - 有没有人解决或解决了 JqGrid 中单元格编辑的一些问题