使用多个成员c ++排序结构

use*_*079 0 c++ sorting structure class

我想对一类"歌曲"数据类型进行排序

class song{
  std::string artist;
  std::string title;
  std::string size;

  public:
};
Run Code Online (Sandbox Code Playgroud)

我知道可以使用bool运算符重载>但如果我想按艺术家排序,然后按标题排序,然后按大小排序,有什么方法可以指定比较顺序吗?

Mar*_*k B 6

在创建时operator<,指定要在比较中使用的属性的顺序.

创建这样的运算符实际上几乎是微不足道的boost::tie(或者std::tie如果你能够使用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);
}
Run Code Online (Sandbox Code Playgroud)