C++中 pair 的用法

#include
#include
#include
using namespace std;

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

	// pair的输出
	cout << "pA : " << pA.first << "  "<< pA.second << endl;
	cout << "pB : " << pB.first << "  "<< pB.second << endl;


	// 结合map的使用
	map mA;
	mapmB;
	mA.insert(pA);
	mB.insert(pB);

	for (map::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::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
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

map m;
pair 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::iterator mit;

    mit = m.begin();

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

    return 0;
}


#include 
#include 
#include 
using namespace std;

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

    pair 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 Author; // 简化声明一个作者pair类型
    Author proust("Marcel", "Proust");
    Author Joyce("James", "Joyce");

    pair next_auth;
    string first, last;
    while (cin >> first >> last) {
        // 使用make_pair函数生成一个新pair对象
        next_auth = make_pair(first, last);
        // 使用make_pair函数,等价于下面这句
        next_auth = pair (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;
}


暂时只会这么简单的用法,刚学到的……



你可能感兴趣的:(ACM_数据结构,小知识)