用于按属性排序对象矢量的C ++模板

时间:2013-10-03 17:37:11

标签: c++ templates sorting c++11 vector

我有一些基于此的工作代码: Sorting a vector of objects by a property of the object

我重新措辞并拿走了许多不必要的东西,让我更容易理解。我仍然无法确切地知道代码在做什么,有人可以评论这段代码或者一步一步地告诉我这里解释发生了什么吗?我对模板的主要内容感到困惑。

#import <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>

using namespace std;


//Can someone please explain this template stuff???
template < typename TYPE, typename MTYPE>
struct member_comparer {

    MTYPE TYPE::*val;

    explicit member_comparer( MTYPE TYPE::*p ) { 
        val = p;
    }

    bool operator ()( TYPE  lhs, TYPE  rhs )  {
        return lhs.*val < rhs.*val;
    }
};



template<typename TYPE, typename MTYPE>
member_comparer<TYPE, MTYPE> make_member_comparer( MTYPE TYPE::*p ) {
    return member_comparer<TYPE, MTYPE>( p );
}

//PLEASE EXPLAIN THE STUFF ABOVE HERE ^





struct Number
{
    //declare our strings
    int i;
    string s;

    //preset the values in the constructor!
    Number( int i, string s ) { 
        this->i = i;
        this->s = s;
    }
};



int main()
{   

    //declare a new vector of Numbers
    vector<Number> vec;

    //fill in the vector
    vec.push_back(Number(2, "two"));
    vec.push_back(Number(8, "eight"));


    // sort by i, ascending
    sort( vec.begin(), vec.end(), make_member_comparer( &Number::i ) );
    cout << vec.front().i << ", " << vec.back().i << "\n";
    //outputs 2, 8


    // sort by s, ascending
    sort( vec.begin(), vec.end(), make_member_comparer( &Number::s ) );
    cout << vec.front().s << ", " << vec.back().s << "\n";
    //outputs eight, two
}

2 个答案:

答案 0 :(得分:1)

template < typename TYPE, typename MTYPE>
struct member_comparer {

MTYPE TYPE::*val;     // public field, a pointer to MTYPE

explicit member_comparer( MTYPE TYPE::*p ) {   // explicit constructor
    val = p;
}

bool operator ()( TYPE  lhs, TYPE  rhs )  {  // operator () (TYPE lhs, TYPE rhs)
                                            // this is typical for a functor
    return lhs.*val < rhs.*val;
}
};


template<typename TYPE, typename MTYPE>
member_comparer<TYPE, MTYPE> make_member_comparer( MTYPE TYPE::*p ) {
    return member_comparer<TYPE, MTYPE>( p );      // return an instance of the functor 
}

答案 1 :(得分:1)

MTYPE TYPE::*val;是来自班级TYPE的成员的指针。该成员的类型为MTYPE

template <typename TYPE, typename MTYPE> struct它是一个由两种类型参数化的结构。 TYPE应该是类MTYPE,它应该是成员的类型。

template<typename TYPE, typename MTYPE>
member_comparer<TYPE, MTYPE> make_member_comparer( MTYPE TYPE::*p ) {
    return member_comparer<TYPE, MTYPE>( p );
}

make_member_comparer是一个避免使用的辅助函数:

member_comparer<Number, int>(&Number::i)