在类中声明向量的大小
Declare size of a vector inside class
我正在尝试声明类中向量的大小。我希望向量大小等于同一类的另一个属性。向量"表">在类哈希表内。"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) { }
//...
相关文章:
- 声明高维向量的更简洁的方法
- 标准::向量声明中使用的模板参数
- 使用全局声明的向量时,C++双重释放错误/损坏
- 为什么这种向量声明无效?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 如何声明一个标准::提升直方图的向量?提升直方图的类型是什么?
- 在类中声明向量的大小
- C++ 通过函数声明后初始化向量
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- 如何声明指向类对象的指针向量?
- 我不明白这个向量声明语句
- <string> C++ 中的向量声明
- 使用更大值和向量声明优先级队列
- 将向量声明为类成员
- 全局和主类中的向量声明
- C++如何将对象的向量声明为类的成员
- 如何将unique_ptr的向量声明为类数据成员?
- 对齐数据类型Eigen::矩阵的数组或向量声明
- 看不懂这个向量声明
- 将对象向量声明为另一个类的成员