c++在函数中创建对象的数组需要在全局范围内使用该数组

c++ creating an array of object in a function need to use the array in global scope

本文关键字:数组 范围内 全局 创建对象 c++ 函数      更新时间:2023-10-16
你好,我正在尝试实现一个可扩展哈希表。我的问题是:我有一个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而不是本地变量。