Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

The C++ container class

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>

Syntax

Here are some basic unordered_set operations:

if (it != uset.end()) { // element exists }

bool isEmpty = uset.empty();

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.