自定义pair模板类 带三个参数

18 篇文章 3 订阅

mypair

#include<iostream>
#include<vector>
#include <algorithm>
#include<map>
using namespace std;

template<typename T1, typename T2, typename T3>
class mypair {
public:
	T1 first;
	T2 second;
	T3 third;
	mypair() :first(T1()), second(T2()), third(T3()) {}
	mypair(const T1& a, const T2& b, const T3& c) :first(a), second(b), third(c) {}

	template<typename t1, typename t2, typename t3>
	friend ostream& operator<<(ostream& out, const mypair<t1, t2, t3>& rhs);
};
template<typename t1, typename t2, typename t3>
 ostream& operator<<(ostream& out, const mypair<t1, t2, t3>& rhs)
{
	out << rhs.first << "   "<<rhs.second<<"   "<<rhs.third<<endl;
	return out;
}

 template<typename s1, typename s2, typename s3>
 inline mypair<s1, s2, s3> make_mypair(const s1& x, const s2& y, const s3& z) {
	 return mypair<s1, s2, s3>(x, y,z);
 }

 template<typename T1, typename T3>	//偏特化版本处理char*,
 inline mypair<T1, string, T3> make_mypair(const T1& x, const char* y, const T3& z) {
	 string str = y;
	 return mypair<T1, string, T3>(x, str, z);
 }


int main()
{
	int n = 10;
	mypair<int, string, int>  pa(0,"hello",100);
	cout <<"test-pa:"<< pa;

	cout << "*************map_tset*****************"<<endl;
	map<int, mypair<int, string, int> > mp;
	mp[0] = pa;
	mp[1] = mypair<int, string, int>(1,"world",20);

	mp.insert(make_pair(2, make_mypair(2,"I come",666)));	
	//此处字符串偏特化处理,很奇怪,vs2019不处理的话,这里的char*不会隐式转换为string

	for (auto it : mp)
	{
		cout << it.second;
	}
	return 0;

}

测试结果:
在这里插入图片描述

pair源码

template <class T1, class T2>
struct pair {
  typedef T1 first_type;
  typedef T2 second_type;

  T1 first;
  T2 second;
  pair() : first(T1()), second(T2()) {}
  pair(const T1& a, const T2& b) : first(a), second(b) {}

#ifdef __STL_MEMBER_TEMPLATES
  template <class U1, class U2>
  pair(const pair<U1, U2>& p) : first(p.first), second(p.second) {}
#endif
};

template <class T1, class T2>
inline bool operator==(const pair<T1, T2>& x, const pair<T1, T2>& y) { 
  return x.first == y.first && x.second == y.second; 
}

template <class T1, class T2>
inline bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y) { 
  return x.first < y.first || (!(y.first < x.first) && x.second < y.second); 
}

template <class T1, class T2>
inline pair<T1, T2> make_pair(const T1& x, const T2& y) {
  return pair<T1, T2>(x, y);
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值