2013-10-03 69 views
1

排序對象的矢量我這是基於關閉的一些這方面的工作代碼: Sorting a vector of objects by a property of the objectC++模板的屬性

我重新措辭,拿出了大量的非必要的東西,使其更容易讓我明白。我仍然無法確切知道代碼在做什麼,有人可以評論這段代碼或者逐步解釋這段代碼嗎?我對模板的主要內容大多感到困惑。

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

回答

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

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)