<utility>是一个很小的头文件。现在其中剩下来的只有模板类pairl、一些与之相关联的模板函数和操作符,以及其他四个模板操作符了。该模板用来将两个对象表示成一个对象--当你想要一个函数返回两个值,或者想用一个容器来存储具有成对值的元素时,这样做就比较方便。
/*utility
pair:对组,可以将两个值(first,second)视为一个单元(pair),是个模板类。
对于map/multimap,就是用pairs来管理value/key的成对元素。任何函数需要
回传两个值,也需要pair */
#include <utility>
#include <string>
#include <iostream>
using namespace std;
void testPairs()
{
pair<string,double> item1("apples",8.75);//定义一个组单元
pair<string,double> item2;
pair<string,double> item3;
item2.first = "chairs";
item2.second = 998;//设置pair的first,second数据
item3 = make_pair("shirts",120.0);//make_pair是个模板函数,返回pair
cout<<"the price of "<<item1.first<<" is $"<<item1.second<<endl;//获取pair的first,second的数据
cout<<"the price of "<<item2.first<<" is $"<<item2.second<<endl;
cout<<"the price of "<<item3.first<<" is $"<<item3.second<<endl;
}
void Test(char key)
{
cout<<"please press key===="<<key<<endl;
switch(key){
case '0':
testPairs();
break;
case 'q':
exit(0);
break;
default:
cout<<"default "<<key<<endl;
break;
}
}
int main()
{
while(1){
Test(getch());
}
system("pause");
return 0;
}