我想对一类“歌曲”数据类型进行排序
class song{
std::string artist;
std::string title;
std::string size;
public:
};
我知道可以使用 bool 运算符重载 > 但是如果我希望它按艺术家排序,然后按标题,然后按大小,有什么方法可以指定比较顺序吗?
When you create your operator<
you specify the order of attributes you wish to use in the comparison.
Creating such operators is actually almost trivial with boost::tie
(or std::tie
if you are able to use C++11):
bool operator<(const song& left, const song& right)
{
return boost::tie(left.artist, left.title, left.size) < boost::tie(right.artist, right.title, right.size);
}
有两种解决方案,或者你有某种全局变量[或类似的],你可以在operator>
函数中访问,或者你使用sort
“比较函数”参数。
第二个解决方案看起来像这样:
class song
{
....
static compareArtist(const song &a, const song &b)
{
return a.artist > b.artist;
}
static compareTitle(const song &a, const song &b)
{
return a.title > b.title;
}
...
}
if (sortby == artist)
sort(songs.begin(), songs.end(), song::compareArtist);
else if (sortby == title)
sort(songs.begin(), songs.end(), song::compareTitle);
每个人似乎都认为您想要基于多个属性的恒定排序。而是将您的“然后”解释为您想在不同时间对不同属性进行排序,这是一个答案:
您可以将 std::sort 与 lambda 一起使用。
std::sort(songs.begin(), songs.end(),
[](const Song& s1, const Song& s2)
{
// any comparison code you want.
return result;
});
You want to overload operator<
not operator>
bool operator<(const song& x, const song& y)
{
if (x.artist < y.artist)
return true;
if (x.artist > y.artist)
return false;
if (x.title < y.title)
return true;
if (x.title > y.title)
return false;
if (x.size < y.size)
return true;
if (x.size > y.size)
return false;
return false;
}
There are any number of variations on this, but that works for me.