Hash sets and hash maps are both data structures that provide fast insertion, deletion, and search operations, but they serve different purposes and have some key differences:
Purpose:
Element Structure:
Accessing Elements:
find()
 or count()
 member functions. You cannot directly access or modify elements in a hash set.[]
 operator or the at()
 member function can be used to retrieve or modify the value associated with a specific key.Ordering:
Here's an example that demonstrates the usage of a hash set and a hash map:
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
int main() {
// Hash Set
std::unordered_set<std::string> uniqueWords;
uniqueWords.insert("apple");
uniqueWords.insert("banana");
// Duplicate, will be ignored
uniqueWords.insert("apple");
std::cout << "Hash Set:" << std::endl;
for (const auto& word : uniqueWords) {
std::cout << word << std::endl;
}
// Hash Map
std::unordered_map<std::string, int> wordCounts;
wordCounts["apple"] = 3;
wordCounts["banana"] = 2;
wordCounts["orange"] = 1;
std::cout << "\nHash Map:" << std::endl;
for (const auto& pair : wordCounts) {
std::cout << pair.first << ": "
<< pair.second << std::endl;
}
}
Hash Set:
apple
banana
Hash Map:
orange: 1
apple: 3
banana: 2
In this example, the hash set uniqueWords
stores unique words, ignoring duplicates. The hash map wordCounts
associates words with their counts, allowing easy retrieval and modification of the counts using the words as keys.
Hash sets are useful when you need to efficiently check the presence of elements and eliminate duplicates, while hash maps are useful when you need to associate values with unique keys and perform fast retrieval and modification of those values based on the keys.
Answers to questions are automatically generated and may not have been reviewed.
This lesson introduces the concept of data structures beyond arrays, and why we may want to use alternatives.