STL-pair-like triplet class - do I roll my own?

前端 未结 5 623
感动是毒
感动是毒 2021-01-03 18:52

I want to use a triplet class, as similar as possible to std::pair. STL doesn\'t seem to have one. I don\'t want to use something too heavy, like Boost. Is there some useful

5条回答
  •  天涯浪人
    2021-01-03 19:26

    I think you need something like this:

    template
    struct triplet
    {
        T first, middle, last;
    };
    
    template
    triplet make_triplet(const T &m1, const T &m2, const T &m3) 
    {
        triplet ans;
        ans.first = m1;
        ans.middle = m2;
        ans.last = m3;
        return ans;
    }
    

    Examples of usage:

    triplet aaa;
    aaa = make_triplet(1.,2.,3.);
    cout << aaa.first << " " << aaa.middle << " "  << aaa.last << endl;
    
    triplet bbb = make_triplet(false,true,false);
    cout << bbb.first << " " << bbb.middle << " "  << bbb.last << endl;
    

    I'm using this and it is enough for my purposes... If you want different types, though, just do some modifications:

    template
    struct triplet
    {
        T1 first; 
        T2 middle;
        T3 last;
    };
    
    template
    triplet make_triplet(const T1 &m1, const T2 &m2, const T3 &m3) 
    {
        triplet ans;
        ans.first = m1;
        ans.middle = m2;
        ans.last = m3;
        return ans;
    }
    

    And the usage will be very similar:

    triplet ccc;
    ccc = make_triplet(false,"AB",3.1415);
    ccc.middle = "PI";
    cout << ccc.first << " " << ccc.middle << " "  << ccc.last << endl;
    

提交回复
热议问题