c++在函数中创建对象的数组需要在全局范围内使用该数组
c++ creating an array of object in a function need to use the array in global scope
你好,我正在尝试实现一个可扩展哈希表。我的问题是:我有一个add函数,我可以决定何时拆分一个bucket,如果拆分它,我需要多少新bucket。所以我在if语句之后创建了一个对象数组。到目前为止没有问题,现在我想在另一个名为的函数中打印数组
std::ostream& print(std::ostream& o)
这是一个使<lt;您可以在Headerfile Container:中看到的运算符
virtual std::ostream& print(std::ostream& o) const = 0;
inline std::ostream& operator<<(std::ostream& o, const Container<E>& c) { return c.print(o); }
所以现在我的添加函数如下:
template <typename E>
void ExHashing<E>::add(const E e[], size_t len) {
if(isfirstBucket(head)){
fill_first_bucket(head, last, e,len,bucket);
}
else {
int number = 2;
Bucket<E> buckets = new Bucket<E>(number);
Bucket<E>* bucket_Pointer = buckets[1];
bucket_Pointer->Set_local_depth(1);
}
}
你可以看到,我制作了一个Bucket对象数组,它运行良好,我不能在打印函数中打印它们,因为那里没有定义Bucket。我的打印功能:
template <typename E>
std::ostream& ExHashing<E>::print(std::ostream& o) const {
size_t number_of_buckets = (1 << global_depth);
for (size_t i = 0; i < number_of_buckets; ++i) {
o << "Bucket size = " << buckets->bucket_size; << " " << "Bucket index = " << buckets[i]->index << " " << "Global depth = " << global_depth << " " << "Local depth = " << buckets[i]->local_depth << "n";
for (size_t j = 0; j < buckets[i]->bucket_size; ++j) {
o << " Bucket value " << "[" << j << "]" << " = " << buckets[i]->displayValues(j)<<"n";
}
}
return o;
}
那么,如何让我的打印函数访问数组桶呢?我不能向函数打印添加参数,因为我刚刚从shell收到命令打印,应该在bucket中显示我的数据。在哪里初始化数组?我不能在构造函数中做这件事,因为我不知道有人要在程序中放入多少数据。
Containers将所持有数据的必要入口点存储为对象的成员。在您的情况下,您将存储指向存储桶的指针(以及您需要的任何其他管理数据):
template <typename E>
class ExHashing {
Bucket<E>* buckets;
public:
ExHashing(): buckets(0) {} // Make sure the pointer is initialized.
ExHashing(ExHashing const&); // You'll likely need a copy ctor,
~ExHashing(); // a destructor,
ExHashing& operator= (ExHashing const&); // and copy assignment.
// as well as other mmebers
};
当您创建或访问bucket时,您将使用this->buckets
而不是本地变量。
相关文章:
- 并行用于C++17中数组索引范围内的循环
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 变量未在此范围内声明 数组线性搜索
- C/C++指针数组的内联强制(void**)
- 对于多个查询,查找在 l 到 r 范围内具有相同元素的最长公共子数组
- C++ 如何在给定范围内将数组中的数字相加?
- 给定数组范围的选择排序问题
- C++ 从指定范围内的文件中读取数组
- gcc8.2如何启用警告:数组下标在数组范围之上[-warray-bounds]
- 为什么我在具有 16 GB 内存的 Mac 上看到数 TB 范围内的 C++ 指针
- 如何计算双打数组中特定范围内的值数量
- 如何通过迭代通过它插入数组范围
- 输出在我的字符数组范围之外,同时使用 rand()
- 数组索引内将变量递增 N
- C++中数组范围内的有效元素计数
- 从字节数组发出内联程序集
- 访问超出数组范围不会产生任何错误
- 在访问多维数组的内置数组和初始化器列表时交换标识符和下标
- 更改函数中的数组值 - 内联程序集
- 为什么我可以设置数组范围之外的值?