C++ container classes<set>

In the C++ standard library<set>is an associative container that stores a set of unique elements and sorts them in a specific order.

<set>Provides efficient element lookup, insertion, and deletion operations. It is implemented based on a red-black tree, and therefore has logarithmic time complexity for lookup, insertion, and deletion.

<set>The element types stored in the container must satisfy the following conditions:

  • The element type must be comparable.
  • The element type must be copyable and assignable.

Syntax

Include the header file:

#include <set>

Declare a set container

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

Common operations

  • insert(元素): Insert an element.
  • erase(元素): Delete an element.
  • find(元素): Find an element.
  • size(): Return the number of elements in the container.
  • empty(): Check whether the container is empty.

Example

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

Example

#include <iostream>
#include <set>

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:

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

<set>is a very useful container in the C++ standard library, especially suitable for scenarios requiring fast lookup, insertion, and deletion operations. Through the above examples, beginners can<set>have a clear understanding of its basic usage. In actual development, making reasonable use of<set>Can improve the efficiency and readability of the program.

other extensions