Checking if a Key Exists without Inserting

How can I check if a key exists in a std::unordered_set without inserting it if it doesn't?

To check if a key exists in a std::unordered_set without inserting it if it doesn't, you can use the find() method. The find() method searches for an element with a specific key and returns an iterator to it if found, or an iterator to end() if not found.

Here's an example:

#include <iostream>
#include <unordered_set>

int main() {
  std::unordered_set<int> Set{1, 2, 3, 4, 5};

  int Key = 3;
  auto it = Set.find(Key);  

  if (it != Set.end()) {
    std::cout << "Key " << Key
      << " exists in the set\n";
  } else {
    std::cout << "Key " << Key
      << " does not exist in the set\n";
  }

  Key = 7;
  it = Set.find(Key);  

  if (it != Set.end()) {
    std::cout << "Key " << Key
      << " exists in the set\n";
  } else {
    std::cout << "Key " << Key
      << " does not exist in the set\n";
  }
}
Key 3 exists in the set
Key 7 does not exist in the set

In this example:

  • We create an unordered set Set with some initial elements
  • We use find() to search for the key 3 in the set. Since 3 exists, find() returns an iterator to the element.
  • We compare the returned iterator with Set.end() to determine if the key was found. If the iterator is not equal to Set.end(), it means the key exists in the set.
  • We then search for the key 7, which doesn't exist in the set. In this case, find() returns an iterator equal to Set.end(), indicating that the key was not found.

Using find() allows you to check for the existence of a key without modifying the set. If the key is not found, no insertion takes place.

Note that if you want to insert the key if it doesn't exist, you can use the insert() method instead. The insert() method returns a pair containing an iterator to the inserted element (or the existing element if the key already exists) and a boolean value indicating whether the insertion took place.

Hash Sets using std::unordered_set

This lesson provides a thorough understanding of std::unordered_set, from basic initialization to handling custom types and collisions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Implementing a Custom Hash Function
How can I implement a custom hash function for my user-defined type to use with std::unordered_set?
Erasing Elements while Iterating
Is it safe to erase elements from a std::unordered_set while iterating over it?
Using a Custom Allocator with std::unordered_set
How can I use a custom allocator with std::unordered_set?
Difference between rehash() and reserve()
What is the difference between rehash() and reserve() in std::unordered_set?
Using std::unordered_set with Smart Pointers
How can I store smart pointers like std::unique_ptr in a std::unordered_set?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant