跳到内容

第五章 STL 容器、算法与流 ​

5.1 std::vector ​

源码出处:dumpsys.cpp:623

cpp
std::vector<pid_t> pids;     // 动态数组,存放 pid_t 元素

语法说明:std::vector<T> 是 C++ 最常用的动态数组容器:连续内存、按下标随机访问 O(1)、尾部追加 O(均摊 1)、自动管理内存。常用操作:push_back、size()、begin()/end()、erase、clear。

注:dumpsys 的服务列表用的是 Android 自研的 android::Vector<T>(dumpsys.cpp:60),接口与 std::vector 相似但略有不同(如 add 对应 push_back,insertAt 对应 insert)。这里客户端 PID 列表用的是标准 std::vector<pid_t>。

最小 demo:

cpp
#include <iostream>
#include <vector>
int main() {
    std::vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    std::cout << "size=" << v.size() << " front=" << v.front() << " [1]=" << v[1] << "\n";
    v.pop_back();                       // 删末尾
    v[0] = 99;
    for (int n : v) std::cout << n << " ";
    std::cout << "\n";
}

运行结果:

size=3 front=10 [1]=20
99 20

5.2 std::set_intersection 求交集 ​

源码出处:dumpsys.cpp:473-477

cpp
Vector<String16> intersection;
std::set_intersection(services.begin(), services.end(),
                      protoServices.begin(), protoServices.end(),
                      std::back_inserter(intersection));
services = std::move(intersection);

语法说明:std::set_intersection 是 <algorithm> 里的算法:对两个已排序的范围求交集,把结果写到输出迭代器。前提是两个输入序列都必须升序排序,否则结果未定义。复杂度 O(n+m)。

最小 demo:

cpp
#include <iostream>
#include <vector>
#include <algorithm>   // set_intersection, sort
int main() {
    std::vector<int> a{1, 2, 3, 5, 8};       // 必须已排序
    std::vector<int> b{2, 3, 4, 8, 9};       // 必须已排序
    std::vector<int> out;
    std::set_intersection(a.begin(), a.end(),
                          b.begin(), b.end(),
                          std::back_inserter(out));   // 结果 {2,3,8}
    for (int n : out) std::cout << n << " ";
    std::cout << "\n";
}

运行结果:

2 3 8

要点:dumpsys 在 --proto 模式下,先取“按优先级过滤的服务列表”和“支持 proto 的服务列表”,两者排序后求交集,得到“既符合优先级又支持 proto”的服务集合。


5.3 erase-remove 惯用法 ​

源码出处:dumpsys.cpp:640-641

cpp
pids.erase(std::remove_if(pids.begin(), pids.end(),
                          [&](pid_t pid) { return pid == myPid; }),
           pids.end());

语法说明:从容器中删除“满足某条件”的所有元素,C++ 标准写法是 erase-remove 惯用法:

  • std::remove_if(begin, end, pred) 并不真的删除元素,而是把不满足 pred 的元素“搬”到容器前部,返回一个指向新逻辑结尾的迭代器 newEnd;
  • 再调用 container.erase(newEnd, end) 真正截断尾部,把多余的元素物理删除。 合起来等价于“删除所有满足 pred 的元素”。C++20 起可直接用 std::erase_if(v, pred)。

最小 demo:

cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> v{1, 2, 3, 2, 4, 2, 5};
    // 删除所有等于 2 的元素
    v.erase(std::remove_if(v.begin(), v.end(),
                           [](int x) { return x == 2; }),
            v.end());
    for (int n : v) std::cout << n << " ";   // 剩 1 3 4 5
    std::cout << "\n";
}

运行结果:

1 3 4 5

要点:dumpsys 用它从客户端 PID 列表里剔除 dumpsys 自身(pid == myPid),因为 dumpsys 自己也持有该 binder 引用,不应算作“被诊断的客户端”。


5.4 std::back_inserter ​

源码出处:dumpsys.cpp:476

cpp
std::back_inserter(intersection)   // 作为 set_intersection 的输出迭代器

语法说明:std::back_inserter(c) 返回一个插入迭代器:对它赋值 *it = x 会调用 c.push_back(x),而不是覆盖已有元素。配合“不知道结果有多大”的算法(如 set_intersection、copy)使用,容器会自动扩容。

最小 demo:

cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> src{1, 2, 3};
    std::vector<int> dst;                     // 空,没有预留空间
    std::copy(src.begin(), src.end(),
              std::back_inserter(dst));        // 每次 += 调 dst.push_back
    for (int n : dst) std::cout << n << " ";
    std::cout << "\n";
}

运行结果:

1 2 3

要点:若直接把 dst.begin() 当输出,会因 dst 为空而越界;back_inserter 保证安全写入。


5.5 std::max ​

源码出处:dumpsys.cpp:836

cpp
return std::max(diff.count(), 0LL);   // 不让剩余时间为负

语法说明:std::max(a, b) 返回两者中较大者;两参数类型需一致(0LL 是 long long 字面量,与 diff.count() 返回类型匹配)。

最小 demo:

cpp
#include <iostream>
#include <algorithm>
int main() {
    long long remaining = -50;
    std::cout << std::max(remaining, 0LL) << "\n";   // 0,避免负数
    std::cout << std::max(3, 7) << "\n";
}

运行结果:

0
7

要点:超时计算里 end - now 在已超时后会是负数,用 std::max(..., 0LL) 把负数钳到 0,确保传给 poll 的不是负超时。


5.6 迭代器 begin/end ​

源码出处:dumpsys.cpp:475, 640

cpp
services.begin(), services.end()        // 半开区间 [begin, end)
pids.begin(), pids.end()

语法说明:迭代器是“泛型指针”,begin() 指向容器首元素,end() 指向末元素之后的位置,构成半开区间 [begin, end)。STL 算法普遍接受 (begin, end) 一对迭代器来表示“要处理的范围”。end() 不解引用,只作哨兵。

最小 demo:

cpp
#include <iostream>
#include <vector>
int main() {
    std::vector<int> v{10, 20, 30};
    auto it = v.begin();               // 指向 10
    std::cout << *it << "\n";          // 10
    ++it;                              // 指向 20
    std::cout << *it << "\n";          // 20
    // 遍历 [begin, end)
    for (auto p = v.begin(); p != v.end(); ++p) std::cout << *p << " ";
    std::cout << "\n";
    std::cout << "size=" << (v.end() - v.begin()) << "\n";   // 随机访问迭代器可相减
}

运行结果:

10
20
10 20 30 
size=3

5.7 std::string 与 std::to_string ​

源码出处:dumpsys.cpp:545, 588-589

cpp
WriteStringToFd(std::to_string(pid) + "\n", fd.get());
WriteStringToFd("Threads in use: " + std::to_string(pidInfo.threadUsage) + "/" +
                    std::to_string(pidInfo.threadCount) + "\n", fd.get());

语法说明:

  • std::string 是 C++ 的字符串类,自动管理内存,支持 + 拼接、+=、size()、c_str()(转 C 风格字符串)等。
  • std::to_string(数值) 把 int/long/double 等转成 std::string,方便与字符串拼接。

最小 demo:

cpp
#include <iostream>
#include <string>
int main() {
    int used = 3, total = 15;
    std::string msg = "Threads in use: " + std::to_string(used) + "/" + std::to_string(total) + "\n";
    std::cout << msg;
    std::string s = "abc";
    s += "def";
    std::cout << s << " len=" << s.size() << "\n";
}

运行结果:

Threads in use: 3/15
abcdef len=6

5.8 std::stringstream + std::put_time ​

源码出处:dumpsys.cpp:907-920

cpp
using std::chrono::system_clock;
const auto finish = system_clock::to_time_t(system_clock::now());
std::tm finish_tm;
localtime_r(&finish, &finish_tm);                  // POSIX:time_t -> tm(线程安全版)
std::stringstream oss;
oss << std::put_time(&finish_tm, "%Y-%m-%d %H:%M:%S");  // 按 fmt 格式化到流
std::string msg = StringPrintf("...ending at: %s\n", ..., oss.str().c_str());

语法说明:

  • std::stringstream 是字符串流,可像 std::cout 一样用 << 往里写各种类型,最后 .str() 取出拼好的 std::string。常用于把多种类型拼成一个字符串。
  • std::put_time(&tm, fmt)(<iomanip>,C++11)把 std::tm 按格式串(同 strftime)格式化写入流,如 "%Y-%m-%d %H:%M:%S" → 2026-11-13 12:34:56。
  • localtime_r 是 POSIX 的可重入版本(_r 后缀),用调用方提供的 tm 缓冲,避免多线程下共享静态缓冲的竞争——比 localtime() 更安全。

最小 demo:

cpp
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctime>
int main() {
    std::time_t now = std::time(nullptr);
    std::tm tmv;
    localtime_r(&now, &tmv);                 // 填充 tmv
    std::stringstream oss;
    oss << std::put_time(&tmv, "%Y-%m-%d %H:%M:%S");
    double secs = 0.123;
    std::string msg = "--------- " + std::to_string(secs).substr(0,5) +
                      "s was the duration, ending at: " + oss.str() + "\n";
    std::cout << msg;
}

运行结果(时间随运行时刻):

--------- 0.123s was the duration, ending at: 2026-11-13 12:34:56

要点:dumpsys footer 形如 --------- 0.123s was the duration of dumpsys foo, ending at: 2026-11-13 12:34:56,正是用 put_time 把挂钟时间格式化后拼进去的。