在类中声明向量的大小

Declare size of a vector inside class

本文关键字:向量 声明      更新时间:2023-10-16

我正在尝试声明类中向量的大小。我希望向量大小等于同一类的另一个属性。向量"表">类哈希表内。"bucket_count">是向量"表">的预期大小。给出的错误是"成员不是类型名称"。请让我知道我可以在类中声明向量大小的另一种方法。如果没有,那么出路是什么?谢谢。 请参考下面的代码。

class HashTable {
public:
int bucket_count;
vector<list<string>> table(bucket_count);
//bool isEmpty(list<string> &cell) const;
int hashFunction(const string& s);
void insertItem(string value);
void removeItem(string value);
bool searchTable(string s);
void printTable();
void processQueries();
void processQuery(const Query& query);
};

我尝试制作一个对我有用的构造函数,但我不确定它为什么有效。

这是我的代码:

HashTable::HashTable(int bc)
: bucket_count(bc)
, table(bucket_count)
{}

在这种情况下,bucket_count在此构造函数中初始化为 bc,这是可以接受的。但是通过该逻辑应该初始化为bc。但事实并非如此。相反,表向量的大小被初始化了(这就是我想要的(。

如果有人能解释一下,为什么构造函数初始化以这种方式工作,那将有很大帮助。

最简单的解决方案是

vector<list<string>> table{(size_t)bucket_count};

这在很大程度上取决于您设置bucket_count的实际值的方式、位置和时间。例如,可以在类构造函数的初始值设定项列表中设置table向量的大小。下面的代码允许您通过在构造函数调用中设置大小来执行此操作,方法是在构造类对象时显式传递大小,或者使用默认值(42我显示的代码中

(:
class HashTable {
public:
int bucket_count;
vector<list<string>> table;
HashTable(int bc = 42) : bucket_count(bc), table(bucket_count) { }
//...

或者,如果bucket_size要保持恒定和通用,您可以使其成为static constexpr成员:

class HashTable {
public:
static constexpr auto bucket_count = 42;
vector<list<string>> table;
HashTable() : table(bucket_count) { }
//...