[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》
相关文章推荐
- [C/C++标准库]_[初级]_[实用类std::pair]
- [C/C++标准库]_[初级]_[std::vector的删除元素]
- [C/C++标准库]_[初级]_[使用std::sort排序各种类型数据]
- [C/C++标准库]_[初级]_[std::vector的多线程读写问题]
- [C/C++标准库]_[初级]_[std::map的使用细节]
- [C/C++标准库]_[初级]_[std::vector的多线程读写问题]
- [C/C++标准库]_[初级]_[std::map的使用细节]
- [C/C++标准库]_[初级]_[如何实现std::string自己的Format(sprintf)函数]
- [C/C++标准库]_[初级]_[std::deque和std::vector比较]
- [C/C++标准库]_[初级]_[如何实现std::string自己的Format(sprintf)函数]
- [C/C++标准库]_[初级]_[std::deque和std::vector比较]
- [C/C++标准库]_[初级]_[自定义std::map的key]
- [C/C++标准库]_[初级]_[自定义std::map的key]
- [C/C++标准库]_[初级]_[std::vector的删除元素]
- [C/C++标准库]_[初级]_[使用std::sort排序各种类型数据]
- [C/C++标准库]_[初级]_[标准库里提供的排序算法]
- [C/C++标准库]_[初级]_[使用string stream]
- [C/C++标准库]_[初级]_[分割字符串Split]
- [C/C++标准库]_[初级]_[转换UTC时间到local本地时间]
- [C/C++]_[初级]_[关于std::string的compare陷阱]