• c++中的工具(一):std::pair<class T1, class T2>


    c++中的函数语法,只能有一个返回值,不像python一样,可以把多个返回值包装到一个元组中,如下

    (x,y) = get_postion(value)

    C++在标准库中定义了工具类std::pair<class T1, class T2>,使C++可以通过相似的方法支持返回两个值。pair的源码类似于:

    namespace std {
        template <class T1, class T2>
        struct pair{
            typedef T1 first_type;
            typedef T2 second_type;
    
            T1 first;
            T2 second;
    
            pair():first(T1(), second(T2())){
    
            }
    
            pair(const T1&a, const T2&b):first(a),second(b){
    
            }
    
            template<class U, class V>
            pair(const pair<U,V>&p):first(p.first), second(p.second){
    
            }
        };
    
        template<class T1, class T2>
        bool operator==(const pair<T1, T2> &x, const pair<T1, T2> &y)
        {
            return x.first == y.first && x.second == y.second;
        }
    
        template<class T1, class T2>
        bool operator< (const pair<T1, T2> &x, const pair<T1, T2> &y)
        {
            return x.first < y.first || (!(x.first < y.first) && (x.second < y.second));
        }
    // > != 等类似

    template
    <class T1, class T2> pair<T1,T2> make_pair(const T1&_first, const T2&_second) { return pair<T1,T2>(_first, _second); } }

    标准库中的std::pair<class T1, class T2>定义在头文件<utility>中。

    std::pair<double, int> getPrice(double unit_price, int amount){
        return std::make_pair(unit_price, amount);
    }
    
    int main()
    {
        std::pair<double, int> info;
        info = getPrice(3.5, 12);
        std::cout << info.first << ":" << info.second << endl;
    }

    在标准库中,容器map就用到了pair来保存自己的每一项。我们在访问map的元素时,可以通过pair类来访问key和value

    #include <iostream>
    #include <map>
    #include <utility>
    
    using namespace std;
    
    int main()
    {
        typedef map<string, float> StringFloatMap;
        StringFloatMap coll;
    
        coll["VAT"] = 0.15;
        coll["Pi"] = 3.1415;
        coll["an arbitrary number"] = 4983.223;
        coll["Null"] = 0;
    
        StringFloatMap::iterator pos;
        for(pos = coll.begin(); pos!=coll.end(); ++pos){
            cout << "key: "" << pos->first << "" "
                 << "value: "" << pos->second << "" "<<endl;
        }
    }
  • 相关阅读:
    50.EasyGank妹纸App
    项目开发规范,数据库设计规范
    用外部物理路由器时与外部dhcp服务时怎样使用metadata服务(by quqi99)
    [报错处理]Python Requests
    [译]为什么在__new __()后总是调用__init __()?
    '>/dev/null 2>&1' 是什么意思?
    “努力就会成功”
    [译]如何在红帽系统(RHEL)上源码安装python3?
    [译]在你的GitHub主页固定仓库
    [译]拉取仓库远程分支
  • 原文地址:https://www.cnblogs.com/mindulmindul/p/12150162.html
Copyright © 2020-2023  润新知