frozen C++ 编译期容器库:完整教程与实战指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

frozen C++ 库:编译期容器完整指南

frozen 是一个仅头文件的 C++17 及以上版本库,提供完全在编译期初始化的容器(map、set、string)。它创建不可变(immutable)数据结构,运行时无需动态内存分配。这是嵌入式系统、游戏引擎、高负载服务器以及对性能和可预测性要求极高的代码的理想解决方案。

frozen 的核心思想是:将容器定义为 constexpr 或 constinit,所有排序、哈希和数据结构构建工作都在编译期完成。运行时,您将获得一个现成的、经过优化的容器,开销极低。例如,frozen::map 使用二分查找对排序数组进行操作,而 frozen::unordered_map 采用完美哈希(perfect hashing),保证 O(1) 访问且无冲突。

对 C++ 开发者而言,这意味着:无动态内存(无 new/delete)、无异常(noexcept)、完全线程安全(数据只读),以及可将容器放置在微控制器的闪存中。该库被 Facebook(现 Meta)、编译器以及操作系统内核广泛使用。

安装方法

frozen 是仅头文件库,安装只需将头文件复制到项目中。最简单的方式是使用 Conan 或 CMake FetchContent。以下是不同包管理器的具体命令。

通过 Conan 安装(推荐)

conan install frozen/1.1.1@ -r conancenter
# 然后在 CMakeLists.txt 中添加:
# find_package(frozen REQUIRED)
# target_link_libraries(your_target frozen::frozen)

通过 vcpkg 安装

vcpkg install frozen
# 安装后使用:
# find_package(frozen CONFIG REQUIRED)
# target_link_libraries(your_target frozen::frozen)

通过 CMake FetchContent 安装(无需包管理器)

include(FetchContent)
FetchContent_Declare(
  frozen
  GIT_REPOSITORY https://github.com/serge-sans-paille/frozen.git
  GIT_TAG v1.1.1
)
FetchContent_MakeAvailable(frozen)
target_link_libraries(your_target frozen::frozen)

手动安装(仅头文件)

git clone https://github.com/serge-sans-paille/frozen.git
# 将 frozen/include/frozen 文件夹复制到您的项目中
# 在编译器中添加 include 路径:
# g++ -I/path/to/frozen/include your_file.cpp -std=c++17

快速入门:最小工作示例

创建文件 example.cpp,内容如下:

#include <iostream>
#include <frozen/unordered_map.h>
#include <frozen/string.h>

int main() {
    // 创建具有完美哈希的编译期 map
    constexpr frozen::unordered_map<frozen::string, int, 3> fruit_calories = {
        {"apple", 95},
        {"banana", 105},
        {"orange", 62}
    };

    // 运行时查找 — O(1),无冲突
    std::cout << "香蕉的卡路里: " << fruit_calories.at("banana") << "\n";

    // 检查键是否存在
    if (auto it = fruit_calories.find("grape"); it != fruit_calories.end()) {
        std::cout << "找到葡萄: " << it->second << "\n";
    } else {
        std::cout << "未找到葡萄\n";
    }

    // 遍历所有元素
    for (auto& [fruit, calories] : fruit_calories) {
        std::cout << fruit.data() <<                    

推荐