網站首頁 編程語言 正文
pair是將2個數據組合成一組數據,當需要這樣的需求時就可以使用pair,如stl中的map就是將key和value放在一起來保存。另一個應用是,當一個函數需要返回2個數據的時候,可以選擇pair。 pair的實現是一個結構體,主要的兩個成員變量是first second 因為是使用struct不是class,所以可以直接使用pair的成員變量。
下面介紹下C++中的pair使用,內容如下所示:
pair基本用法
pair<string, int> p1("hello world", 233);
cout << p1.first << " " << p1.second;
p1 = make_pair("lala", 322);
pair 其他使用
重載pair的加減運算符
// 加法
template<class Ty1,class Ty2>
inline const pair<Ty1,Ty2> operator+(const pair<Ty1, Ty2>&p1, const pair<Ty1, Ty2>&p2)
{
pair<Ty1, Ty2> ret;
ret.first = p1.first + p2.first;
ret.second = p1.second + p2.second;
return ret;
}
// 減法
template<class Ty1, class Ty2>
inline const pair<Ty1, Ty2> operator-(const pair<Ty1, Ty2>&p1, const pair<Ty1, Ty2>&p2)
{
pair<Ty1, Ty2> ret;
ret.first = p1.first - p2.first;
ret.second = p1.second - p2.second;
return ret;
}
在vector中使用
// 初始化舉例
vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
// 添加新元素幾種方式
// make_pair
dirs.push_back(make_pair(2,2));
// 初始化構造函數
dirs.push_back(pair<int, int>(2,2));
// 聚合初始化
dirs.push_back({2,2});
// emplace_back
dirs.emplace_back(2,2);
補充:下面看下c++的pair用法
在實際的工作中,經常需要用到pair的內容,然后每次呢,我都會由于忘記pair怎么用的而需要去百度,我個人覺得很麻煩,于是想著自己總結一下,這樣,以后看自己寫的也可以更方便直接一點。
因為主要是寫給自己看的,所以,我將主要以代碼的形式來展示pair相關的用法:
#include <iostream>
using namespace std;
int main(){
std::pair<std::string,int> pr;
pr.first = "first";
pr.second = 1;
std::pair<std::string,int>pr2("second",2);
std::pair<std::string,int>pr3 = std::make_pair("third",3);
std::pair<std::string,std::pair<int,float>>pr4=std::make_pair("four",std::make_pair(1,1.0f));
printf("%-8s:%d\n",pr.first.c_str(),pr.second);
printf("%-8s:%d\n",pr2.first.c_str(),pr2.second);
printf("%-8s:%d\n",pr3.first.c_str(),pr3.second);
printf("%-8s:%d,%.3f\n",pr4.first.c_str(),pr4.second.first,pr4.second.second);
return 0;
}
輸出結果如下:
first :1
second :2
third :3
four :1,1.000
原文鏈接:https://www.cnblogs.com/Timinup/p/16661712.html
相關推薦
- 2022-08-21 Android貝塞爾曲線實現加入購物車拋物線動畫_Android
- 2022-09-02 Python用matplotlib庫畫圖中文和負號顯示為方框的問題解決_python
- 2022-03-23 Linux和GNU系統的關系詳解_Linux
- 2022-06-12 教你十行代碼實現python向手機推送通知功能_python
- 2022-09-26 Python文件相關操作和方法匯總大全_python
- 2022-07-29 使用React?Router?v6?添加身份驗證的方法_React
- 2022-01-11 Cookie、sessionStorage和localStorage的區別
- 2022-03-14 跨域問題Response to preflight request doesn't pass acc
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支