STL的头文件中描述了一个看上去非常简单的模板类pair,用来表示一个二元组或元素对,并提供了按照字典序对元素对进行大小比较的比较运算符模板函数。

例如,想要定义一个对象表示一个平面坐标点,则可以:

pair p1;
cin >> p1.first >> p1.second;

pair模板类需要两个参数:首元素的数据类型和尾元素的数据类型。pair模板类对象有两个成员:first和second,分别表示首元素和尾元素。

中已经定义了pair上的六个比较运算符:<、>、<=、>=、==、!=,其规则是先比较first,first相等时再比较second,这符合大多数应用的逻辑。当然,也可以通过重载这几个运算符来重新指定自己的比较逻辑。

除了直接定义一个pair对象外,如果需要即时生成一个pair对象,也可以调用在中定义的一个模板函数:make_pair。make_pair需要两个参数,分别为元素对的首元素和尾元素。

在题1067--Ugly Numbers中,就可以用pair来表示推演树上的结点,用first表示结点的值,用second表示结点是由父结点乘以哪一个因子得到的。

#include
#include

using namespace std;

typedef pair node_type;

main()
{
unsigned long result[1500];
priority_queue< node_type, vector, greater > Q;
Q.push( make_pair(1, 2) );
for (int i=0; i<1500; i++)
{
node_type node = Q.top(); Q.pop();
switch(node.second)
{
case 2: Q.push( make_pair(node.first*2, 2) );
case 3: Q.push( make_pair(node.first*3, 3) );
case 5: Q.push( make_pair(node.first*5, 5) );
}
result[i] = node.first;
}

int n;
cin >> n;
while (n>0)
{
cout << result[n-1] << endl;
cin >> n;
}

return 1;
}

看上去是很简单的一个头文件,但是的设计中却浓缩反映了STL设计的基本思想。有意深入了解和研究STL的同学,仔细阅读和体会这个简单的头文件,不失为一种入门的途径。




Comments

Good.Be the first to comment on this entry.

Post comment

comment has COPYRIGHT too!

Note: Commenter is allowed to use '@User+blank' to automatically notify your reply to other commenter. e.g, if ABC is one of commenter of this post, then write '@ABC '(exclude ') will automatically send your comment to ABC. Using '@all ' to notify all previous commenters. Be sure that the value of User should exactly match with commenter's name (case sensitive).