一、pair的理解
可以把pair理解成C中的sprintf,存放链接两种类型数据,访问第一种使用first,访问第二种数据使用second。
二、pair的使用
基本使用:
#include <iostream>
#include <utility>
using namespace std;
int main()
{
pair <string,string> student(小明,三班);
cout<<student.first<<student.second<<endl;
return 0;
}
运行结果:
小明三班
pair与类结合使用:以下实例用test类对象作为pair的第二个存储数据,同时使用到了构造函数二号this指针。
#include <iostream>
#include <utility>
using namespace std;
class test
{
public:
string str_data;
test(string str_data)
{
this->str_data = str_data;//初始化成员变量str_data;
cout<<str_data<<endl;
}
};
int main()
{
string str_data = "hello";
test test_one("world");
pair <string,test> pair_test(str_data,test_one);
cout<<pair_test.first<<pair_test.second.str_data<<endl;//输出pair变量中的数据
return 0;
}
输出结果:
world
helloworld