I want to store a objects with a custom comparator function in a C++ std::map
, e.g.:
std::map<Part, Inventory, PartCmp>
For the comparator, I would like to sort the objects by a "key" that could be expensive to compute, so I thought about a lazy evaluation method. The below example is kind of trivial but illustrates the problem:
class Part {
public:
std::string item_id;
int color_id;
int condition;
std::string name;
std::string category;
std::string key();
private:
std::string key_;
}
std::string Part::key() {
// Only create key value if it hasn't been done before
if (key_.empty()) {
ostringstream keystream;
keystream << item_id << color_id << condition;
key_ = keystream.str();
}
return key_;
}
This means my comparator looks this:
struct PartCmp {
bool operator() (Part& p1, Part& p2) const {
return p1.key() < p2.key();
}
};
This is different from every other example I've seen where p1
and p2
are declared as const
parameters.
However, in this case p1
and p2
cannot be declared as const
since the key()
method modify its respective objects. The code compiles but is this a bad thing to do?