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

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

猜你喜欢

转载自www.cnblogs.com/mindulmindul/p/12150162.html
t1