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

来源:互联网 发布:人工智能瓶颈问题 编辑:程序博客网 时间:2024/05/21 17:44


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;}

输出:

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


参考:

1. 《C++ Standard Library, The: A Tutorial and Reference》



0 0
原创粉丝点击