c++ pair

定义 typedef pair<int,string>p;

定义的p相当于struct

举个栗子:

#include<iostream>
#include<cstdio>
using namespace std;
typedef pair<int,string>p;
struct ac{
    int first;
    string second;
};
int main()
{
    p a;
    ac b;
    cin>>a.first>>a.second;
    cin>>b.first>>b.second;
    cout<<"a: "<<a.first<<" "<<a.second<<endl;
    cout<<"b: "<<b.first<<" "<<b.second<<endl;
    return 0;
}

输入:

1 a.first

2 b.first

输出:

a: 1 a.first
b: 2 b.first

03-08
### C++ 中 `pair` 的用法 在 C++ 标准库中,`std::pair` 是一种用于存储两个不同类型数据的容器模板。通过使用 `std::make_pair()` 函数可以方便地创建一对值。 #### 创建和初始化 `pair` 可以直接定义并初始化一个 `pair`: ```cpp #include <utility> // For std::pair and std::make_pair #include <iostream> int main() { // 定义并初始化 pair std::pair<int, double> p1(10, 3.14); // 使用 make_pair 初始化 std::pair<std::string, int> p2 = std::make_pair(std::string("hello"), 42); // 输出 pairs std::cout << "Pair 1: (" << p1.first << ", " << p1.second << ")" << std::endl; std::cout << "Pair 2: (" << p2.first << ", " << p2.second << ")" << std::endl; return 0; } ``` #### 访问 `pair` 成员 可以通过 `.first` 和 `.second` 来访问 `pair` 中的第一个和第二个成员[^1]。 #### 遍历 map 或 multimap 当遍历像 `std::map` 这样的关联容器时,迭代器指向的是键值对类型的元素——即 `std::pair<const Key, T>` 类型的对象。因此,在遍历时可以直接解构这些对象以便于操作其内部的数据。 ```cpp #include <map> #include <iostream> void traverseMap(const std::map<int, std::string>& my_map) { for (const auto& pair : my_map) { std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl; } } int main() { std::map<int, std::string> example{{1, "one"}, {2, "two"}}; traverseMap(example); return 0; } ``` 上述代码展示了如何利用范围 for 循环来遍历 `std::map` 并打印其中每项的键和对应的值。 #### 可变参数宏中的注意事项 需要注意的是,在某些情况下(比如编写可变参数宏),如果涉及到 `__VA_OPT__` 关键字,则应遵循特定规则以避免编译错误。例如,C++ 不允许在可变参数宏体外的地方使用此关键字[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值