[英]how to store multiple values under same key using hashing in c++
我想使用散列技术在c ++中创建电话目录项目。我需要做的一件事是它必须基于location搜索联系人,因此我将位置作为键值,但同一位置将有多个联系人。所以如何在同一键(位置)下存储多个值(名称,电话号码)。
If you are using C++11 or newer, you could use std::unordered_multimap
to store multiple entries per key (eg multiple entries per location). 如果您使用的是C ++ 11或更高版本,则可以使用std::unordered_multimap
每个键存储多个条目(例如,每个位置存储多个条目)。 It is a hash map that allows multiple entries with the same key. 它是一个哈希图,允许使用同一键的多个条目。 To store multiple properties per entry, you can use a struct or class. 要为每个条目存储多个属性,可以使用结构或类。 Finally, it could look like this: 最后,它可能看起来像这样:
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;
}
}
However, consider that values with the same key are not sorted. 但是,请考虑未对具有相同键的值进行排序。 You may want to use something like std::unordered_map<std::string, std::multiset<contact_t>>
instead. 您可能想使用类似std::unordered_map<std::string, std::multiset<contact_t>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.