您的位置:首页 > 编程语言 > C语言/C++

[C/C++标准库]_[初级]_[实用类std::pair]

2014-04-18 19:23 387 查看

std::pair

场景:

1. 在需要元数据信息时,pair发挥比较大的作用,比如对返回值的额外信息描述就可以用pair,不需要额外创建一个关联类.

2. 而且pair是模版类,适合不同类型的对象.

3. 写这么小的类估计会被Java童鞋鄙视吧,呵呵。

说明:

1. 在进行operator==比较时,也是对first,second对象调用operator==比较.

2. 在进行operator < 比较时,先比较first的operator <,如果first ==,那么调用second的operator <.

3.在map里和multimap中使用pair存储key/value.

#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <utility>

using namespace std;

pair<int,string> DoSomeWork(bool flag)
{
	if (flag)
	{
		return std::make_pair(-1,string("Network is disconnect!"));
	}else
	{
		return pair<int,string>(0,"Success.");
	}
}

int main(int argc, char const *argv[])
{
	//原始类型如果用这种创建方式,是初始化为0.
	int i = int();
	cout << i << endl;

	pair<int,string> res = DoSomeWork(true);
	cout << "code: " << res.first << " description: " << res.second << endl;

	res = DoSomeWork(false);
	cout << "code: " << res.first << " description: " << res.second << endl;

	return 0;
}


输出:

0
code: -1 description: Network is disconnect!
code: 0 description: Success.


参考:

1. 《C++ Standard Library, The: A Tutorial and Reference》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: