首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在STL中使用unordered_set?

在C++中,unordered_set是一个关联容器,它使用哈希表来存储数据。unordered_set的主要特点是它提供了快速的查找、插入和删除操作。要在STL中使用unordered_set,请按照以下步骤操作:

  1. 包含所需的头文件:
代码语言:cpp
复制
#include<iostream>
#include <unordered_set>
  1. 声明一个unordered_set变量:
代码语言:cpp
复制
std::unordered_set<int> my_set;
  1. unordered_set中添加元素:
代码语言:cpp
复制
my_set.insert(10);
my_set.insert(20);
my_set.insert(30);
  1. 查找元素:
代码语言:cpp
复制
if (my_set.find(20) != my_set.end()) {
    std::cout << "Element 20 found in the set."<< std::endl;
} else {
    std::cout << "Element 20 not found in the set."<< std::endl;
}
  1. 删除元素:
代码语言:cpp
复制
my_set.erase(10);
  1. 遍历unordered_set中的元素:
代码语言:cpp
复制
for (auto it = my_set.begin(); it != my_set.end(); ++it) {
    std::cout << "Element: " << *it<< std::endl;
}

以下是一个完整的示例:

代码语言:cpp
复制
#include<iostream>
#include <unordered_set>

int main() {
    std::unordered_set<int> my_set;

    my_set.insert(10);
    my_set.insert(20);
    my_set.insert(30);

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

    my_set.erase(10);

    for (auto it = my_set.begin(); it != my_set.end(); ++it) {
        std::cout << "Element: " << *it<< std::endl;
    }

    return 0;
}

这个示例展示了如何在STL中使用unordered_set来存储和操作整数。你可以根据需要替换整数类型为其他数据类型。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

34秒

PS使用教程:如何在Photoshop中合并可见图层?

3分54秒

PS使用教程:如何在Mac版Photoshop中制作烟花效果?

36秒

PS使用教程:如何在Mac版Photoshop中画出对称的图案?

1分6秒

PS使用教程:如何在Mac版Photoshop中制作“3D”立体文字?

3分25秒

063_在python中完成输入和输出_input_print

1.3K
6分36秒

070_导入模块的作用_hello_dunder_双下划线

125
4分32秒

060_汉语拼音变量名_蛇形命名法_驼峰命名法

354
7分34秒

069_ dir_函数_得到当前作用域的所有变量列表_builtins

445
5分8秒

055_python编程_容易出现的问题_函数名的重新赋值_print_int

1.4K
5分14秒

064_命令行工作流的总结_vim_shell_python

367
4分36秒

04、mysql系列之查询窗口的使用

3分47秒

python中下划线是什么意思_underscore_理解_声明与赋值_改名字

928
领券