有点困惑,我无法找到与我的问题有关的任何内容。我可能会以错误的方式问它。
我有这段代码:
#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;
}
但是双重值的赋值似乎并没有在对象产生之后开始。
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
我应该以不同的方式做这件事吗?有什么建议。万分感谢。
答案 0 :(得分:2)
问题出在这里:
addItem(name, 0.00); // you construct new price item
return price->price; // but here you return ref to some other item.
检查上面的评论。