STL - 容器 - UnorderedSet(一)

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
简介: 一些简单操作 UnorderedSetTest.cpp #include #include #include "../../Core/print.hpp" #include "UnorderedSetTest.

一些简单操作

UnorderedSetTest.cpp

#include <unordered_set>
#include <numeric>
#include "../../Core/print.hpp"
#include "UnorderedSetTest.h"

using namespace std;

void UnorderedSetTest::simpleOperation()
{
    // create and initialize unordered set
    unordered_set<int> coll = { 1, 2, 3, 5, 7, 11, 13, 17, 19, 77 };

    // print elements
    // - elements are in arbitrary order
    PRINT_ELEMENTS(coll);

    // insert some additional elements
    // - might cause rehashing and create different order
    coll.insert({ -7, 17, 33, -11, 17, 19, 1, 13 });
    PRINT_ELEMENTS(coll);

    // remove element with specific value
    coll.erase(33);

    // insert sum of all existing values
    coll.insert(accumulate(coll.begin(), coll.end(), 0));
    PRINT_ELEMENTS(coll);

    // check if value 19 is in the set
    if (coll.find(19) != coll.end()) 
    {
        cout << "19 is available" << endl;
    }

    // remove all negative values
    unordered_set<int>::iterator pos;
    for (pos = coll.begin(); pos != coll.end();) 
    {
        if (*pos < 0) {
            pos = coll.erase(pos);
        }
        else {
            ++pos;
        }
    }

    PRINT_ELEMENTS(coll);
}

void UnorderedSetTest::run()
{
    printStart("simpleOperation()");
    simpleOperation();
    printEnd("simpleOperation()");
}

运行结果:

---------------- simpleOperation(): Run Start ----------------
17 1 2 19 11 3 77 13 5 7
17 1 2 19 11 3 77 13 5 7 -7 33 -11
17 1 2 19 11 3 77 13 5 7 -7 -11 137
19 is available
17 1 2 19 11 3 77 13 5 7 137
---------------- simpleOperation(): Run End ----------------

目录
相关文章
|
10月前
|
存储 缓存 C++
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
C++ 标准模板库(STL)提供了一组功能强大的容器类,用于存储和操作数据集合。不同的容器具有独特的特性和应用场景,因此选择合适的容器对于程序的性能和代码的可读性至关重要。对于刚接触 C++ 的开发者来说,了解这些容器的基础知识以及它们的特点是迈向高效编程的重要一步。本文将详细介绍 C++ 常用的容器,包括序列容器(`std::vector`、`std::array`、`std::list`、`std::deque`)、关联容器(`std::set`、`std::map`)和无序容器(`std::unordered_set`、`std::unordered_map`),全面解析它们的特点、用法
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
|
存储 搜索推荐 C++
【C++篇】深度剖析C++ STL:玩转 list 容器,解锁高效编程的秘密武器2
【C++篇】深度剖析C++ STL:玩转 list 容器,解锁高效编程的秘密武器
231 2
【C++篇】深度剖析C++ STL:玩转 list 容器,解锁高效编程的秘密武器2
|
存储 C++ 容器
【C++篇】深度剖析C++ STL:玩转 list 容器,解锁高效编程的秘密武器1
【C++篇】深度剖析C++ STL:玩转 list 容器,解锁高效编程的秘密武器
233 5
|
存储 编译器 C++
【C++篇】揭开 C++ STL list 容器的神秘面纱:从底层设计到高效应用的全景解析(附源码)
【C++篇】揭开 C++ STL list 容器的神秘面纱:从底层设计到高效应用的全景解析(附源码)
233 2
|
安全 编译器 容器
C++STL容器和智能指针
C++STL容器和智能指针
|
存储 算法 C语言
【C++】详解STL的适配器容器之一:优先级队列 priority_queue
【C++】详解STL的适配器容器之一:优先级队列 priority_queue
|
设计模式 存储 缓存
【C++】详解STL容器之一的deque和适配器stack,queue
【C++】详解STL容器之一的deque和适配器stack,queue
|
存储 算法 C++
【C++】详解STL容器之一的 vector
【C++】详解STL容器之一的 vector
|
算法 C语言 C++
【C++】详解STL的容器之一:list
【C++】详解STL的容器之一:list
|
C++ 容器
C++ STL标准库 《map容器详解》
C++ STL标准库 《map容器详解》
136 0