我想使用散列技术在 C++ 中制作一个电话目录项目。我需要做的一件事是它必须根据位置搜索联系人。所以我会将位置作为键值,但会有多个联系人相同的位置。那么如何在相同的键(位置)下存储多个值(姓名,电话号码)。
最佳答案
如果您使用的是 C++11 或更新版本,您可以使用 std::unordered_multimap
每个键存储多个条目(例如每个位置多个条目)。它是一个 HashMap ,允许多个条目具有相同的键。要为每个条目存储多个属性,您可以使用结构或类。最后,它可能看起来像这样:
struct contact_t {
std::string name;
std::string phone_number;
}
std::unordered_multimap<std::string, contact_t> directory;
int main(int argc, char *argv[])
{
// Add entry
contact_t contact;
contact.name = "Fooman";
contact.phone_number = "00 000 00000000";
directory.emplace("Barcity", contact);
// List all entries of one city
auto range = directory.equal_range("Barcity");
for (auto it = range.first; it != range.second; ++it) {
auto &entry = it->second; // it->first would be the key/location
std::cout << "Name: " << entry.name
<< "Phone: " << entry.phone_number << std::endl;
}
}
但是,请考虑具有相同键的值未排序。你可能想使用类似 std::unordered_map<std::string, std::multiset<contact_t>>
的东西相反。
关于c++ - 如何在 C++ 中使用哈希在同一个键下存储多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467412/