gpt4 book ai didi

c++为对象分配重载数组索引运算符

转载 作者:行者123 更新时间:2023-11-28 02:15:38 24 4
gpt4 key购买 nike

有点困惑,我找不到与我的问题有关的任何内容。我可能问错了方式。

我有这个代码:

#include <iostream>
#include <string>

class AssociativeArray {
public:
AssociativeArray(){
for (int i = 0; i < tableSize; i++) {
HashTable[i] = new item;
HashTable[i]->name = "empty";
HashTable[i]->price = 0.00;
HashTable[i]->next = NULL;
}
}
int HashKey(std::string key) {
int hash = 0;
int index;

for (int i = 0; i < key.length(); i++) {
hash = hash + (int)key[i];
}
index = hash % tableSize;
return index;
}
void addItem(std::string name, double price) {
int index = HashKey(name);
if (HashTable[index]->name == "empty") {
HashTable[index]->name = name;
HashTable[index]->price = price;
}
else {
item* ptr = HashTable[index];
item* n = new item;
n->name = name;
n->price = price;
n->next = NULL;

while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = n;
}
}
double& findPrice(std::string name) {
int index = HashKey(name);
bool found = false;

item* ptr = HashTable[index];
item* price = ptr;

while (ptr != NULL) {
if (ptr->name == name) {
found = true;
price = ptr;
}
ptr = ptr->next;
}
if (found == true) {
return price->price;
}
else {
addItem(name, 0.00);

return price->price;
}
}
double& operator[](std::string name) {
return findPrice(name);
}

private:
static const int tableSize = 5;
struct item {
std::string name;
double price;
item* next;
};

item* HashTable[tableSize];
};
int main() {

AssociativeArray prices;

prices.addItem("Socks", 10.96);

std::cout << prices["Socks"] << std::endl;
prices["Socks"] = 7.77;
std::cout << prices["Socks"] << std::endl;

prices["Toaster Oven"] = 19.95;
std::cout << prices["Toaster Oven"] << std::endl; //Print 0.00, doesn't update price!
prices["Toaster Oven"] = 19.95; //update the price!?
std::cout << prices["Toaster Oven"] << std::endl;

system("PAUSE");
return 0;
}

基本上,我试图通过散列来创建一个数组。我认为我错误地重载了 [] 运算符。由于某种原因,分配不允许项目更新。有任何想法吗?任何帮助或只是朝着正确的方向插入都会有所帮助!

我现在的方法是,当调用 operator[] 时找不到对象时,将一个新对象写入该项目的散列中。如下所示:

    while (ptr != NULL) {
if (ptr->name == name) {
found = true;
price = ptr;
}
ptr = ptr->next;
}
if (found == true) {
return price->price;
}
else {
addItem(name, 0.00);

return price->price;
}

但是 double 值的赋值似乎要等到对象创建之后才会开始。

prices["Toaster Oven"] = 19.95;
std::cout << prices["Toaster Oven"] << std::endl; //Prints 0.00 Doesn't work

prices["Toaster Oven"] = 19.95;
std::cout << prices["Toaster Oven"] << std::endl; //Prints 19.95 works

我应该换一种方式吗?有什么建议。非常感谢。

最佳答案

问题在这里:

addItem(name, 0.00); // you construct new price item
return price->price; // but here you return ref to some other item.

检查上面的评论。

关于c++为对象分配重载数组索引运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34124781/

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