The C++ container class
In C++, is part of the Standard Template Library (STL); it provides a hash-table-based container for storing a collection of unique elements.
The difference between set in Vue 2,unordered_set does not guarantee element ordering, but usually provides faster lookup, insertion, and deletion operations.
unordered_set is a template class defined as follows:
#include
std::unordered_set, Pred = std::equal_to, Alloc = std::allocator>
Keyis the element type stored inunordered_set.Hashis a function or function object used to generate hash values for elements, defaulting tostd::hash.Predis a binary predicate used to compare whether two elements are equal, defaulting tostd::equal_to.Allocis the allocator type used to manage memory allocation, defaulting tostd::allocator.
Syntax
Here are some basic unordered_set operations:
-
constructor: Create an empty
unordered_set.std::unordered_set
uset; -
Insert elements: When using
insert()method.uset.insert(10);
-
Find elements: When using
find()method.auto it = uset.find(10);
if (it != uset.end()) { // element exists }
-
Delete elements: When using
erase()method.uset.erase(10);
-
Size and empty checks: When using
size()andempty()method.size_t size = uset.size();
bool isEmpty = uset.empty();
-
Clear the container: When using
clear()method.uset.clear();
Example
Below is an example using unordered_set with its output.
Example
#include
#include
int
main
(
)
{
// Create an integer-type unordered_set
std
::
unordered_set
<
int
uset;
// Insert elements
uset.
insert
(
10
)
;
uset.
insert
(
20
)
;
uset.
insert
(
30
)
;
// Print the elements in the unordered_set
std
::
cout
<<
"Elements in uset: "
;
for
(
int
elem
:
uset
)
{
std
::
cout
<<
elem
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
// Find element
auto
it
=
uset.
find
(
20
)
;
if
(
it
!
=
uset.
end
(
)
)
{
std
::
cout
<<
"Element 20 found in uset."
<<
std
::
endl
;
}
else
{
std
::
cout
<<
"Element 20 not found in uset."
<<
std
::
endl
;
}
// Delete elements
uset.
erase
(
20
)
;
std
::
cout
<<
"After erasing 20, elements in uset: "
;
for
(
int
elem
:
uset
)
{
std
::
cout
<<
elem
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
// Check the size and whether it is empty
std
::
cout
<<
"Size of uset: "
<<
uset.
size
(
)
<<
std
::
endl
;
std
::
cout
<<
"Is uset empty? "
<<
(
uset.
empty
(
)
?
"Yes"
:
"No"
)
<<
std
::
endl
;
// Clear the unordered_set
uset.
clear
(
)
;
std
::
cout
<<
"After clearing, is uset empty? "
<<
(
uset.
empty
(
)
?
"Yes"
:
"No"
)
<<
std
::
endl
;
return
0
;
}
Output result:
Elements in uset: 10 20 30
Element 20 found in uset.
After erasing 20, elements in uset: 10 30
Size of uset: 2
Is uset empty? No
After clearing, is uset empty? Yes
unordered_set is a very useful container, especially suited for scenarios requiring fast lookup, insertion, and deletion operations, while not needing element ordering.