gpt4 book ai didi

c++ - 哈希表的复制构造函数

转载 作者:行者123 更新时间:2023-11-28 02:14:21 25 4
gpt4 key购买 nike

我在为哈希表编写复制构造函数时遇到了问题。我已经在单独使用链接对象的复制构造函数方面遇到了麻烦。如何使用以下函数实现复制构造函数和赋值运算符:

//copy constructor
Apple::Apple(const Apple& anotherApple){


}

//assignment operator
Apple& Apple::operator = (const Apple& anotherApple){


}

我知道它会是这样的:

tableSize = anotherApple.tableSize;
count = anotherApple.count;
array = new *anotherApple.array; //idk if this is right for dynamically created array of pointers

最佳答案

Apple::Apple(Apple const & anotherApple)
{
// allocate an array to hold pointers to Node
array = new Node*[tableSize];

for(int i=0; i<tableSize; i++)
{
Node* src = anotherApple.array[i];
Node* dest;

if (src == NULL)
{
array[i] = NULL;
continue; // no data to copy, continue to next row
}


// set array[i] since there is at-least one element
dest = new Node;
dest->data = src->data;

array[i] = dest;
src = src->next;

while(src != NULL)
{
Node* n = new Node;
dest->next = n;
dest = n;

dest->data = src->data;

src = src->next;
}

dest->next = NULL;
}
}

关于c++ - 哈希表的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com