蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 std::unordered_set 唯一插入、查找删除清空、自定义哈希谓词与桶负载

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-libs-unordered-set.cpp
explore-cpp-libs-unordered-set.cpp154 行
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

struct Tag {
    int id;
    std::string label;
};

struct TagHash {
    std::size_t operator()(const Tag& t) const noexcept {
        return std::hash<int>{}(t.id) ^ (std::hash<std::string>{}(t.label) << 1);
    }
};

struct TagEqual {
    bool operator()(const Tag& a, const Tag& b) const noexcept {
        return a.id == b.id && a.label == b.label;
    }
};

int main() {
    std::vector<lab::Case> cases;

    // Case 1: construct, insert unique elements and reject duplicates
    std::unordered_set<int> uset;
    auto r1 = uset.insert(10);
    auto r2 = uset.insert(20);
    auto r3 = uset.insert(30);
    auto rdup = uset.insert(20);
    std::vector<int> sorted_elems(uset.begin(), uset.end());
    std::sort(sorted_elems.begin(), sorted_elems.end());
    std::string elem_str;
    for (std::size_t i = 0; i < sorted_elems.size(); ++i) {
        if (i) elem_str += ",";
        elem_str += std::to_string(sorted_elems[i]);
    }
    bool ok1 = r1.second && r2.second && r3.second && !rdup.second && uset.size() == 3 && elem_str == "10,20,30";
    cases.push_back({
        "unordered_set_insert_unique",
        lab::esc("size=3;dup=0;elems=10,20,30"),
        lab::esc("size=" + std::to_string(uset.size()) + ";dup=" + std::to_string(rdup.second ? 1 : 0) + ";elems=" + elem_str),
        ok1
    });

    // Case 2: find, erase, size, empty, clear
    bool found20 = (uset.find(20) != uset.end());
    std::size_t erased = uset.erase(20);
    bool found20_after = (uset.find(20) != uset.end());
    std::size_t sz_after_erase = uset.size();
    bool empty_before_clear = uset.empty();
    uset.clear();
    bool empty_after_clear = uset.empty();
    std::string act2 = "found=" + std::to_string(found20 ? 1 : 0)
        + ";erased=" + std::to_string(erased)
        + ";after=" + std::to_string(found20_after ? 1 : 0)
        + ";size=" + std::to_string(sz_after_erase)
        + ";emptyBefore=" + std::to_string(empty_before_clear ? 1 : 0)
        + ";emptyAfter=" + std::to_string(empty_after_clear ? 1 : 0);
    std::string exp2 = "found=1;erased=1;after=0;size=2;emptyBefore=0;emptyAfter=1";
    cases.push_back({
        "unordered_set_find_erase_clear",
        lab::esc(exp2),
        lab::esc(act2),
        act2 == exp2
    });

    // Case 3: custom Hash and Pred template arguments
    std::unordered_set<Tag, TagHash, TagEqual> tags;
    tags.insert({1, "alpha"});
    tags.insert({2, "beta"});
    bool dup_tag = tags.insert({1, "alpha"}).second;
    bool hit_beta = (tags.find({2, "beta"}) != tags.end());
    std::string act3 = "size=" + std::to_string(tags.size()) + ";dup=" + std::to_string(dup_tag ? 1 : 0) + ";hit=" + std::to_string(hit_beta ? 1 : 0);
    std::string exp3 = "size=2;dup=0;hit=1";
    cases.push_back({
        "unordered_set_custom_hash_pred",
        lab::esc(exp3),
        lab::esc(act3),
        act3 == exp3
    });

    // Case 4: bucket interface and reserve/count
    std::unordered_set<int> bset;
    bset.reserve(32);
    for (int i = 1; i <= 10; ++i) bset.insert(i * 10);
    bool ok4 = (bset.bucket_count() >= 32)
        && (bset.load_factor() <= bset.max_load_factor())
        && (bset.count(50) == 1)
        && (bset.count(55) == 0);
    cases.push_back({
        "unordered_set_bucket_load_factor",
        lab::jbool(true),
        lab::jbool(ok4),
        ok4
    });

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-libs-unordered-set-lab/explore-cpp-libs-unordered-set.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-libs-unordered-set.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2376.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习