0

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?

jasonm76
  • 500
  • 2
  • 13

1 Answers1

5

You might want to declare the field

private:
   mutable std::string key_;

See this question.

And also, as suggested by a comment from juanchopanza, make your key() method const

At last, I believe you are more doing some memoization, not some lazy evaluation.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547