C++中 pair 的使用方法

#include<iostream>
#include<string>
#include<map>
using namespace std;

// pair简单讲就是将两个数据整合成一个数据
// 本质上是有first, second两个成员变量的结构体
int main()
{
	// pair两种构造的方法
	// 方法1
	pair<string, double> pA("one", 1.11);// 浮点数默认是double, float的话有会警告。

// 方法2 pair<string, int> pB; pB = make_pair("two", 2); // pair的输出 cout << "pA : " << pA.first << " "<< pA.second << endl; cout << "pB : " << pB.first << " "<< pB.second << endl; // 结合map的使用 map<string, double> mA; map<string,int>mB; mA.insert(pA); mB.insert(pB); for (map<string, double>::iterator it = mA.begin(); it != mA.end(); ++it) { cout << "First Member of mA: " << it->first << endl; cout << "Second Member of mA: " << it->second << endl; } for (map<string, int>::iterator it = mB.begin(); it != mB.end(); ++it) { cout << "First Member of mB: " << it->first << endl; cout << "Second Member of mB: " << it->second << endl; } return 0; }





#include<algorithm>
#include<iostream>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<string>
#include<map>
#include<set>
using namespace std;

map<string, int> m;
pair<string,int> p;

int main() {

    p = make_pair("one",1);//make_pair(),返回一个pair类型

    cout << p.first << endl;//输出p的key,也就是"one";

    cout << p.second << endl;//输出p的value,也就是1

    m.insert(make_pair("two",2));

    map<string, int>::iterator mit;

    mit = m.begin();

    cout << mit->first << endl;
    
    cout << mit->second << endl;//分别输出“two”。和2

    return 0;
}


#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    pair<string, string> anon;    // 包括两个字符串
    pair<string, int> word_count; // 包括字符串和整数
    pair<string, vector<int> > line; // 包括字符串和一个int容器

    pair<string, string> author("James", "Joyce"); // 定义成员时初始化
    cout << author.first << " - " << author.second << endl;

    string firstBook;             // 使用 . 訪问和測试pair数据成员
    if (author.first == "James" && author.second == "Joyce") {
        firstBook = "Stephen Hero";
        cout << firstBook << endl;
    }

    typedef pair<string, string> Author; // 简化声明一个作者pair类型
    Author proust("Marcel", "Proust");
    Author Joyce("James", "Joyce");

    pair<string, string> next_auth;
    string first, last;
    while (cin >> first >> last) {
        // 使用make_pair函数生成一个新pair对象
        next_auth = make_pair(first, last);
        // 使用make_pair函数,等价于以下这句
        next_auth = pair<string, string> (first, last);

        cout << next_auth.first << " - " << next_auth.second << endl;
        if (next_auth.first == next_auth.second)
            break; // 输入两个相等,退出循环
    }

    cout <<  "由于pair的数据成员是共同拥有的。因而能够直接读取输入" << endl;
    while (cin >> next_auth.first >> next_auth.second) {

        cout << next_auth.first << " - " << next_auth.second << endl;
        if (next_auth.first == next_auth.second)
            break;
    }

    return 0;
}


临时仅仅会这么简单的使用方法。刚学到的……



posted @ 2017-06-09 15:30  yangykaifa  阅读(347)  评论(0编辑  收藏  举报