C++ 标准库 - <utility>

C++ std::pair<T1, T2> 是两个成员的聚合:first 与 second。也可用 std::make_pair 推导类型。

原型

template<class T1, class T2>
struct pair { T1 first; T2 second; };

参数

  • 两个类型参数分别为两个成员的类型。

返回值

对象本身;成员可直接读写(若未 const)。

示例

#include <iostream>
#include <string>
#include <utility>

int main() {
    std::pair<std::string, int> p{"Ada", 95};
    std::cout << p.first << " " << p.second << "\n";
    return 0;
}

输出:

Ada 95

注意事项

map 里每个元素都是 pair<const Key, T>,所以 it->first 是键,it->second 是值。

下一页介绍swap。