Skip to content

Abseil — Google 工具库

Abseil 是 Google 开源的 C++ 基础库,包含高性能容器、字符串工具、时间库、同步原语等,是 Google 内部代码的精华提炼。

安装

bash
# vcpkg
vcpkg install abseil

# CMake
find_package(absl REQUIRED)
target_link_libraries(myapp PRIVATE absl::strings absl::flat_hash_map absl::time)

高性能容器

cpp
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/btree_map.h"

// flat_hash_map:比 std::unordered_map 快 2-3x
// 开放寻址,缓存友好,内存紧凑
absl::flat_hash_map<std::string, int> map;
map["key"] = 42;
map.reserve(1000);  // 预分配

// flat_hash_set
absl::flat_hash_set<int> set = {1, 2, 3, 4, 5};
set.contains(3);  // true

// btree_map:有序,比 std::map 更缓存友好
absl::btree_map<std::string, int> ordered;
ordered["a"] = 1;
ordered["b"] = 2;
// 支持范围查询,比 std::map 快

字符串工具

cpp
#include "absl/strings/str_split.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"

// 字符串拼接(比 + 运算符高效)
std::string s = absl::StrCat("Hello", ", ", "World", "!", 42);

// 格式化(类似 printf,但类型安全)
std::string s2 = absl::StrFormat("name=%s, age=%d", "Alice", 30);

// 分割
std::vector<std::string> parts = absl::StrSplit("a,b,c", ',');
std::vector<absl::string_view> views = absl::StrSplit("a,b,c", ',');

// 跳过空字符串
auto parts2 = absl::StrSplit("a,,b,,c", ',', absl::SkipEmpty());

// 连接
std::vector<std::string> words = {"hello", "world"};
std::string joined = absl::StrJoin(words, ", ");

// 替换
std::string result = absl::StrReplaceAll("hello world", {{"hello", "hi"}, {"world", "C++"}});

// 检查
absl::StartsWith("hello", "he");
absl::EndsWith("hello", "lo");
absl::StrContains("hello world", "world");

时间库

cpp
#include "absl/time/time.h"
#include "absl/time/clock.h"

// 当前时间
absl::Time now = absl::Now();

// 时间格式化
std::string s = absl::FormatTime("%Y-%m-%d %H:%M:%S", now, absl::LocalTimeZone());
std::string utc = absl::FormatTime(absl::RFC3339_full, now, absl::UTCTimeZone());

// 时间解析
absl::Time t;
std::string err;
absl::ParseTime("%Y-%m-%d", "2026-04-23", absl::UTCTimeZone(), &t, &err);

// 时间运算
absl::Time future = now + absl::Hours(24);
absl::Duration diff = future - now;
std::cout << absl::ToInt64Hours(diff) << " 小时\n";

// Duration
absl::Duration d = absl::Seconds(30) + absl::Milliseconds(500);
absl::SleepFor(absl::Milliseconds(100));

状态码(absl::Status)

cpp
#include "absl/status/status.h"
#include "absl/status/statusor.h"

// 返回状态
absl::Status validate(int age) {
    if (age < 0) return absl::InvalidArgumentError("年龄不能为负");
    if (age > 150) return absl::OutOfRangeError("年龄超出范围");
    return absl::OkStatus();
}

// 返回值或错误(类似 Rust Result)
absl::StatusOr<int> parse_age(std::string_view s) {
    int age;
    if (!absl::SimpleAtoi(s, &age)) {
        return absl::InvalidArgumentError(absl::StrCat("无效的年龄: ", s));
    }
    return age;
}

// 使用
auto result = parse_age("30");
if (result.ok()) {
    std::cout << "年龄: " << *result << "\n";
} else {
    std::cerr << result.status() << "\n";
}

// 宏简化错误传播
#define RETURN_IF_ERROR(expr) \
    do { auto _s = (expr); if (!_s.ok()) return _s; } while(0)

absl::Status process() {
    RETURN_IF_ERROR(validate(25));
    // ...
    return absl::OkStatus();
}

关键认知

Abseil 的 flat_hash_mapstd::unordered_map 的高性能替代,在大多数场景快 2-3x。absl::Status/absl::StatusOr 是 Google 风格的错误处理方式,比异常更显式。absl::StrCat 比字符串 + 运算符更高效(减少内存分配)。

系统学习 C++ 生态,深入底层架构