#include <cstring>
class Item
{
private:
int id;
char name[32];
public:
Item(const int id = 0, const char *name = nullptr)
{
this->id = id;
if(!name)
::strcpy(this->name, "");
else
::strcpy(this->name, name);
}
const int getId() const
{
return id;
}
const char* getName() const
{
return name;
}
bool operator<(const Item another) const
{
return this->id < another.id;
}
bool operator>(const Item another) const
{
return this->id > another.id;
}
};
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<Item> ItemVector;
int main(int argc, char **argv)
{
ItemVector itemVector;
itemVector.push_back(Item(2, "アイテム2"));
itemVector.push_back(Item(4, "アイテム4"));
itemVector.push_back(Item(1, "アイテム1"));
itemVector.push_back(Item(3, "アイテム3"));
itemVector.push_back(Item(0, "アイテム0"));
stable_sort(itemVector.begin(), itemVector.end(), [](const Item& a, const Item& b) { return a < b; } );
for(ItemVector::iterator iter = itemVector.begin();
iter != itemVector.end();
++iter) {
printf("%d: %s\n", iter->getId(), iter->getName());
}
return 0;
}
コンパイル時に比較演算子をconstメンバにしないとコンパイルできないのは何故なのでしょうか。