版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34784043/article/details/82963507
C++中的pair对组的本质是一个struct类型的模板,所以它具有struct的特征,就是可以把不同的数据据类型合成一个结构体类型,不同的是pair只能合成两种数据类型。
下面是对组的用法,用程序注释解释:
#include <iostream>
#include <string>
#include <map>
#include <cstdlib>
using namespace std;
int main() {
//初始化对组方法一,使用构造函数
/* pair构造函数的定义为
_CONST_FUN pair(const _Ty1& _Val1, const _Ty2& _Val2)
: first(_Val1), second(_Val2)
{ // construct from specified values
}
*/
pair<string, int> person(string("name"), 18);
//初始化对组方法二,使用make_pair,效果同方法一
/* make_pair原型为
make_pair(_Ty1&& _Val1, _Ty2&& _Val2)
{ // return pair composed from arguments
typedef pair<typename _Unrefwrap<_Ty1>::type,
typename _Unrefwrap<_Ty2>::type> _Mypair;
return (_Mypair(_STD forward<_Ty1>(_Val1),
_STD forward<_Ty2>(_Val2)));
}
*/
class Student {
private:
string name;
int id;
int age;
public:
string show()
{
return "StudentClass";
}
};
Student stu;
pair<Student, int> student = make_pair(stu, 18);
//输出对组的元素,第一个元素使用first,第二个元素使用second
/* pair的原型是一个结构体模板,first和second是其中两个变量
template<class _Ty1,
class _Ty2>
struct pair
{ // store a pair of values
...
_Ty1 first; // the first stored value
_Ty2 second; // the second stored value
};
*/
cout << "person: " << person.first << " " << person.second << endl;
cout << "student:" << student.first.show() << " " << student.second << endl;
//常使用pair给map插入值
map<string, int> mapPerson;
mapPerson.insert(person);
//输出map中的值
for (map<string, int>::iterator iter = mapPerson.begin(); iter != mapPerson.end(); iter++)
{
cout << "mapPerson:" << iter->first << " " << iter->second << endl;
}
system("pause");
return 0;
}
C++中除了对组,还有一个tuple对组,它是对组的泛化,可以随意把任意个数的数据类型合成一个元组类型。
本人元组文章:https://blog.csdn.net/qq_34784043/article/details/82964423