Hash Sets using std::unordered_set

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?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved