STL之pair对组
1. 对组
对组(pair)将一对值组合成一个值,这一对值可以具有不同的数据类型,两个值可以分别用pair的两个公有属性first和second访问。
类模板:template <class T1, class T2> struct pair.
如何创建对组?
代码示例:
//第一种方法创建一个对组 pair<string, int> pair1(string("name"), 20); cout << pair1.first << endl; //访问pair第一个值 cout << pair1.second << endl;//访问pair第二个值 //第二种 pair<string, int> pair2 = make_pair("name", 30); cout << pair2.first << endl; cout << pair2.second << endl; //pair=赋值 pair<string, int> pair3 = pair2; cout << pair3.first << endl; cout << pair3.second << endl;
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> using namespace std; void test() { // pair<string, int>p(string("Tom"), 100); cout << "姓名" << p.first << endl; cout << "年龄" << p.second << endl; pair<string, int>p2 = make_pair("Jerry", 200); cout << "姓名:" << p2.first << endl; cout << "年龄:" << p2.second << endl; } class Person { public: Person(string name, int age) :m_name(name), m_age(age) {} string m_name; int m_age; }; void test01() { Person p1("金刚狼", 20); //Person p1("金刚狼", 20); //Person p1("金刚狼", 20); pair<int, Person>s1(10, p1); cout << s1.second.m_age << s1.second.m_name << endl; cout << s1.first << endl; } int main(){ test01(); //test(); system("pause"); return EXIT_SUCCESS; }

浙公网安备 33010602011771号