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# winform组件 怎样集成

    在C# WinForms应用程序中集成组件通常涉及以下几个步骤: 添加引用: 首先,确保你已经安装了所需的组件。例如,如果你想要集成一个第三方库,你需要将该库的DLL...

  • c# winform组件 怎样提高效率

    要提高C# WinForms应用程序的效率,可以从多个方面入手,包括优化绘图过程、使用异步操作、合理设置控件属性等。以下是一些具体的优化策略:
    优化绘图过程 ...

  • c# winform组件 怎样自定义

    在C#中,要自定义WinForms组件,您需要创建一个继承自现有控件的新类,并重写其构造函数、事件处理程序和其他相关方法。以下是一个简单的示例,说明如何创建一个...

  • c# winform组件 怎样选择合适

    在C# WinForms应用程序开发中,选择合适的组件对于构建高效、用户友好的界面至关重要。以下是一些选择合适组件的建议:
    控件选择 根据需求选择:选择控件时...

  • 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
    ...