我有一个类说class stuff{ int id; int ammount; int quality; /*...*/ };
我有一个 vector<stuff> items
.我想让我的收藏按 stuff::id
排序并可通过 staff::id
搜索.我可以通过 find_if 来完成,并使用一些基于 STL lambda 的特殊排序函数进行排序。但是我想在 vector 中默认拥有这一切。我听说有一些方法可以创建散列函数,但我四处搜索都找不到它...那么如何使用默认 vector 函数使类在 vector 内部可排序/可搜索?
最佳答案
为了排序,实现一个 operator<
比较两个结构:
bool operator<(const stuff& s1, const stuff& s2)
{
// Your comparison here
}
这是大多数排序默认使用的运算符。
为了进行相等性检查,创建一个 operator==
同样。
关于c++ - 如何使类在 vector 内可排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273308/