c++pair的用法

来源:互联网 发布:淘宝女童模特小苹果 编辑:程序博客网 时间:2024/04/30 05:21

pair 类也是标准库的一部分它使得我们可以在单个对象内部把相同类型或不同类型的

两个值关联起来为了使用pair 类我们必须包含下面的头文件
#include <utility>
例如
pair< string, string > author( "James", "Joyce" );
创建了一个pair 对象author 它包含两个字符串分别被初始化为James 和Joyce
我们可以用成员访问符号member access notation 访问pair 中的单个元素它们的名
字为first 和second 例如
string firstBook;
if ( author.first == "James" &&
author.second == "Joyce" )

firstBook = "Stephen Hero";


如果我们希望定义大量相同pair 类型的对象那么最方便的做法就是用typedef 如下所

typedef pair< string, string > Authors;
Authors proust( "marcel", "proust" );
Authors joyce( "james", "joyce" );

Authors musil( "robert", "musil" );


下面是第二个pair 一个元素持有对象的名字另一个元素持有指向其符号表入口的指


// 前向声明(forward declaration)
class EntrySlot;
extern EntrySlot* look_up( string );
typedef pair< string, EntrySlot* > SymbolEntry;
SymbolEntry current_entry( "author", look_up( "author" ));
// ...
if ( EntrySlot *it = look_up( "editor" ))
{
current_entry.first = "editor";
current_entry.second = it;

}


定义方法:


1     pair<int, double> p1;  //使用默认构造函数2     pair<int, double> p2(1, 2.4);  //用给定值初始化3     pair<int, double> p3(p2);  //拷贝构造函数

访问元素:

1     pair<int, double> p1;  //使用默认构造函数2     p1.first = 1;3     p1.second = 2.5;4     cout << p1.first << ' ' << p1.second << endl;

赋值


1  利用make_pair

1     pair<int, double> p1;2     p1 = make_pair(1, 1.2);

2变量间相互赋值


  pair<int, double> p1(1, 1.2);    pair<int, double> p2 = p1;

0 0
原创粉丝点击