C++ count()
Anonymous contributor
Published Feb 11, 2026
The count() method in C++ checks whether a given key exists in a std::unordered_set. Since this container stores only unique elements, count() will always return one of these two values:
1: If the element is found in the set.0: If the element is not found in the set.
This method is commonly used as a fast, O(1) average time complexity way to check for element existence.
Syntax
unordered_set_name.count(key);
Parameters:
key(const Key&): The value of the element to search for. Must be of the same type as the elements stored in theunordered_set.
Return value:
Returns an integer. 1 if the element exists, 0 otherwise.
Example
This example demonstrates using count() to check for the presence of elements within a set of strings:
#include <iostream>#include <string>#include <unordered_set>int main() {std::unordered_set<std::string> inventory = {"Sword","Shield","Potion"};std::cout << "Inventory contains:\n";for (const auto& item : inventory) {std::cout << "- " << item << "\n";}// Check for an existing elementif (inventory.count("Sword")) {std::cout << "\n'Sword' is present (Count: " << inventory.count("Sword") << ").\n";}// Check for a missing elementif (inventory.count("Axe") == 0) {std::cout << "'Axe' is not present (Count: " << inventory.count("Axe") << ").\n";}return 0;}
The output of the code is:
Inventory contains:- Potion- Shield- Sword'Sword' is present (Count: 1).'Axe' is not present (Count: 0).
Codebyte Example
Run the codebyte below to check for the presence of an item in a set of integers:
All contributors
- Anonymous contributor
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours