117.info
人生若只如初见

C++的set容器怎样使用

C++ 的 set 容器是一种关联式容器,它包含一组唯一的对象。每个元素在插入时都会自动按键进行排序。set 容器通常使用红黑树实现,因此插入、删除和查找操作的时间复杂度都是 O(log n)。

以下是使用 C++ set 容器的基本步骤:

  1. 包含头文件:
#include 
#include 
  1. 创建一个 set 对象:
std::set my_set;
  1. set 中插入元素:
my_set.insert(5);
my_set.insert(3);
my_set.insert(7);
my_set.insert(1);
  1. 检查元素是否存在于 set 中:
if (my_set.find(3) != my_set.end()) {
    std::cout << "3 is in the set." << std::endl;
} else {
    std::cout << "3 is not in the set." << std::endl;
}
  1. 删除元素:
my_set.erase(3);
  1. 遍历 set 中的元素:
for (const auto& element : my_set) {
    std::cout << element << " ";
}
std::cout << std::endl;
  1. 获取 set 的大小和容量:
std::cout << "Size of the set: " << my_set.size() << std::endl;
std::cout << "Capacity of the set: " << my_set.capacity() << std::endl;
  1. 清空 set
my_set.clear();
  1. 销毁 set 对象:

set 对象离开其作用域时,它会自动被销毁。

以下是一个完整的示例程序:

#include 
#include 

int main() {
    std::set my_set;

    my_set.insert(5);
    my_set.insert(3);
    my_set.insert(7);
    my_set.insert(1);

    std::cout << "Size of the set: " << my_set.size() << std::endl;

    for (const auto& element : my_set) {
        std::cout << element << " ";
    }
    std::cout << std::endl;

    if (my_set.find(3) != my_set.end()) {
        std::cout << "3 is in the set." << std::endl;
    } else {
        std::cout << "3 is not in the set." << std::endl;
    }

    my_set.erase(3);

    if (my_set.find(3) != my_set.end()) {
        std::cout << "3 is in the set." << std::endl;
    } else {
        std::cout << "3 is not in the set." << std::endl;
    }

    return 0;
}

输出结果:

Size of the set: 4
1 5 7 3 
Size of the set: 3
1 5 7 

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe9e8AzsKAQZSDFw.html

推荐文章

  • c#编写记事本代码如何写

    在C#中,你可以使用WinForms或WPF来创建一个简单的记事本应用程序。这里我将为你提供一个使用WinForms的示例代码: 首先,创建一个新的Windows Forms应用程序项目...

  • c# vue框架winform怎么使用

    在C#中使用Vue.js与WinForms结合通常意味着你希望在WinForms应用程序中嵌入一个Vue.js的前端应用。这可以通过以下步骤实现: 创建Vue.js项目:首先,你需要创建一...

  • c# tablelayoutpanel怎么使用

    在C#中,TableLayoutPanel是一个强大的控件,用于创建和管理多个行和列的表格布局。以下是如何使用TableLayoutPanel的基本步骤: 添加TableLayoutPanel控件: 在...

  • c++如何执行shell脚本

    在C++中,你可以使用system()函数来执行Shell脚本
    #include #include int main() { // 要执行的Shell脚本文件路径 std::string scriptPath = "/path/to/you...

  • Linux C++编译器能生成调试信息吗

    是的,Linux上的C++编译器可以生成调试信息
    例如,使用g++编译器时,可以通过添加-g选项来生成调试信息:
    g++ -g -o my_program my_program.cpp 这里,...

  • Linux C++编译器怎样处理编译警告

    在Linux系统中,C++编译器(如g++)会生成编译警告,以帮助开发者识别潜在的问题 使用-Wall选项:这个选项会开启所有常见的编译警告。例如,使用g++ -Wall myfil...

  • Linux C++编译器如何查看编译日志

    在Linux系统中,使用C++编译器(如g++或clang++)编译程序时,可以通过以下方法查看编译日志: 使用-v或--verbose选项:
    当使用g++或clang++编译程序时,添...

  • Linux C++编译器适用于哪些系统

    Linux C++编译器主要适用于多种Linux发行版,包括但不限于以下几种: Ubuntu
    Debian
    RHEL (Red Hat Enterprise Linux)
    CentOS
    Fedora
    ...