2025年4月25日,GCC15.1.0正式发布。新版本增加了对新语法特性和标准库的支持,本文挑选一些内容进行介绍。

import std

GCC15添加了对 modules 的支持,可以直接使用 import 语句导入模块。

// main.cpp
import std;
int main() {
    std::println("hello world!");
}

如果是第一次编译含有 import std 这种导入标准模块的代码,需要首先运行以下命令编译标准模块。

g++ -std=c++26 -fmodules -fsearch-include-path bits/std.cc

编译完标准模块后,就可以编译上面的C++代码段了。使用以下命令进行编译。

g++ -o main main.cpp -std=c++23 -fmodules

最后输入 ./main 运行程序,就可以看到 hello world! 的输出了。需要注意的是,在 Windows 上要添加 -lstdc++exp 参数才能正常使用 std::println

flat_set, flat_map

std::flat_set是一种容器适配器,提供与std::set类似的功能。std::flat_set与std::set的一大区别是,std::set的底层数据结构是红黑树,而std::flat_set的底层数据结构是有序数组,默认为std::vector。

由于std::flat_set采用数组作为底层数据结构,它的插入和删除操作的时间复杂度为O(n),查找操作的时间复杂度与std::set相同,都是O(log(n))。

不过,正因为std::flat_set采用有序数组保存数据,它拥有更好的内存连续性,同时,它的迭代器也从std::set的双向迭代器变为随机访问迭代器。

格式化范围

GCC15支持范围的格式化,现在可以直接使用std::println输出std::vector、std::set等容器了。

#include <print>
#include <set>
#include <map>
#include <vector>

int main() {
    std::set<int> s{2, 3, 4};
    std::println("{}", s);

    std::vector<int> v{1, 3, 5, 7};
    std::println("{}", v);

    std::map<char, int> m{{'h', 1}, {'e', 1}, {'l', 2}, {'o', 1}};
    std::println("{}", m);
}

以上代码输出内容如下:

{2, 3, 4}
[1, 3, 5, 7]
{'e': 1, 'h': 1, 'l': 2, 'o': 1}
最后修改:2025 年 05 月 12 日
如果觉得我的文章对你有用,请随意赞赏