[英]how to store multiple values under same key using hashing in c++
我想使用散列技術在c ++中創建電話目錄項目。我需要做的一件事是它必須基於location搜索聯系人,因此我將位置作為鍵值,但同一位置將有多個聯系人。所以如何在同一鍵(位置)下存儲多個值(名稱,電話號碼)。
如果您使用的是C ++ 11或更高版本,則可以使用std::unordered_multimap
每個鍵存儲多個條目(例如,每個位置存儲多個條目)。 它是一個哈希圖,允許使用同一鍵的多個條目。 要為每個條目存儲多個屬性,可以使用結構或類。 最后,它可能看起來像這樣:
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>>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.