gpt4 book ai didi

按属性对对象 vector 进行排序的 C++ 模板

转载 作者:行者123 更新时间:2023-11-30 04:13:55 25 4
gpt4 key购买 nike

我有一些基于此的工作代码: 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
}

最佳答案

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
}

关于按属性对对象 vector 进行排序的 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19165605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com