我想使用散列技术在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). 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.