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

The C++ standard library's is an associative container that stores a set of unique elements and sorts them in a certain order.

provides efficient element lookup, insertion, and deletion operations. It is implemented based on a red-black tree, so it has logarithmic time complexity for lookup, insertion, and deletion.

The element type stored in the container must satisfy the following conditions:

Syntax

Include the header file:

#include 

Declare a set container

std::set<元素类型> 容器名;

common operations

Example

Below is an example using simple example, including element insertion, lookup, deletion, and output results.

Example

#include

#include

int

main

(

)

{

   

// Declare an integer set container

    std

::

set

<

int

mySet

;

   

// Insert elements

    mySet.

insert

(

10

)

;

    mySet.

insert

(

20

)

;

    mySet.

insert

(

30

)

;

    mySet.

insert

(

40

)

;

   

// Output the elements in the set

    std

::

cout

<<

"Set contains: "

;

   

for

(

int

num

:

mySet

)

{

        std

::

cout

<<

num

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

// Find element

   

if

(

mySet.

find

(

20

)

!

=

mySet.

end

(

)

)

{

        std

::

cout

<<

"20 is in the set."

<<

std

::

endl

;

   

}

else

{

        std

::

cout

<<

"20 is not in the set."

<<

std

::

endl

;

   

}

   

// Delete elements

    mySet.

erase

(

20

)

;

   

// Output the elements in the set again

    std

::

cout

<<

"After erasing 20, set contains: "

;

   

for

(

int

num

:

mySet

)

{

        std

::

cout

<<

num

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

// Check whether the set is empty

   

if

(

mySet.

empty

(

)

)

{

        std

::

cout

<<

"The set is empty."

<<

std

::

endl

;

   

}

else

{

        std

::

cout

<<

"The set is not empty."

<<

std

::

endl

;

   

}

   

// Output the number of elements in the set

    std

::

cout

<<

"The set contains "

<<

mySet.

size

(

)

<<

" elements."

<<

std

::

endl

;

   

return

0

;

}

Output result:

Set contains: 10 20 30 40 

20 is in the set.

After erasing 20, set contains: 10 30 40 

The set is not empty.

The set contains 3 elements.

Summary

is a very useful container in the C++ standard library, especially suited for scenarios requiring fast lookup, insertion, and deletion operations. Through the above example, beginners can gain a clear understanding of 's basic usage. In actual development, using reasonably can improve the program's efficiency and readability.