经过大量研究并试图解决这个问题
我想知道是否有办法在C ++中订购对象列表;
到目前为止我见过的所有解决方案,我们必须先定义哪个阵营将用于排序。
我想要的是让用户自由选择他想用来排序的阵营这是我的代码
class LOL
{
public:
LOL( const string& Nickname = "", int skill = 0,int level= 0 );
bool operator > ( const LOL &rhs ) const;
void print() const;
private:
int level_;
string Nickname_;
int skill_;
};
inline
LOL::LOL( const string& Nickname, int skill, int level)
: level_( level), Nickname_( Nickname ), skill_( skill )
{}
inline
bool LOL::operator > ( const LOL& rhs ) const
{ return Nickname_ > rhs.Nickname_; }
inline
void LOL::print() const
{ cout << Nickname_ << " from level " << level_
<< " has skill of [ " << skill_ <<" ]"<< endl<< endl;
}
int main( )
{
list<LOL> list1;
list1.push_back( LOL( "Dhespair", 50000, 30 ) );
list1.push_back( LOL( "Pedro", 1, 1 ) );
list1.push_back( LOL( "Blackblood", 99999, 30 ) );
list1.push_back( LOL( "Zladovic", 30000, 25 ) );
list1.sort( greater <LOL>() );
for_each( list1.begin(), list1.end(), mem_fun_ref( &LOL::print ) );
printf("\n\n");
system("pause");
}
经过几次尝试,我想出了这个解决方案
class LOL
{
public:
LOL( const string& Nickname = "", int skill = 0,int level= 0 , int op=1);
bool operator > ( const LOL &rhs ) const; // MUDAR O > para maior ou < MENOR
bool operator < ( const LOL &rhs ) const; // MUDAR O > para maior ou < MENOR
void print() const;
private:
int level_;
string Nickname_;
int skill_;
int op_;
};
inline
LOL::LOL( const string& Nickname, int skill, int level, int op)
: level_( level), Nickname_( Nickname ), skill_( skill ), op_( op )
{}
inline
bool LOL::operator > ( const LOL& rhs ) const
{
switch(rhs.op_)
{
case 1:
return Nickname_ > rhs.Nickname_;
break;
case 2:
return level_ > rhs.level_;
break;
case 3:
return skill_ > rhs.skill_;
break;
} // MUDAR O > para maior ou < MENOR e ESCOLHER CAMPO A TER EM CONTA
}
inline
bool LOL::operator < ( const LOL& rhs ) const
{
switch(rhs.op_)
{
case 1:
return Nickname_ < rhs.Nickname_;
break;
case 2:
return level_ < rhs.level_;
break;
case 3:
return skill_ < rhs.skill_;
break;
} // MUDAR O > para maior ou < MENOR e ESCOLHER CAMPO A TER EM CONTA
}
inline
void LOL::print() const
{ cout << Nickname_ << " from level " << level_
<< " has skill of [ " << skill_ <<" ]"<< endl<< endl;
}
int main( )
{
list<LOL> list1;
list1.push_back( LOL( "Dhespair", 50000, 30,3 ) );
list1.push_back( LOL( "Pedro", 1, 1,3 ) );
list1.push_back( LOL( "Blackblood", 99999, 30,3) );
list1.push_back( LOL( "Zladovic", 30000, 25,3 ) );
list1.sort( less <LOL>() );
for_each( list1.begin(), list1.end(), mem_fun_ref( &LOL::print ) );
printf("\n\n");
system("pause");
}
我所做的是我的对象有一个新值,我将用它来操作bool操作符内的switch case。
它可以工作,但如果有人知道使用该开关的方法而不必在我的对象中有一个新参数,我会真正适应x)
最好的问候
答案 0 :(得分:0)
bool compareTwoLOLObjectsWay1(LOL &A, LOL &B)
{
/* Logic to determine if A<B */
}
bool compareTwoLOLObjectsWay2(LOL &A, LOL &B)
{
/* Logic to determine if A>B */
}
switch(sortWay)
{
case 1:
list1.sort(&compareTwoLOLObjectsWay1);
break;
case 2:
list1.sort(&compareTwoLOLObjectsWay2);
break;
}