0
我要存儲一個對象與在C++ std::map
自定義比較器功能,如:C++懶密鑰生成比較功能
std::map<Part, Inventory, PartCmp>
對於比較,我想通過一個「關鍵對象進行排序「這可能是昂貴的計算,所以我想到了一個懶惰的評估方法。下面的例子是一種微不足道,但足以說明問題:
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_;
}
這意味着我比較期待這樣的:
struct PartCmp {
bool operator() (Part& p1, Part& p2) const {
return p1.key() < p2.key();
}
};
這是我見過的每一個其他例子p1
和p2
聲明不同如const
參數。
但是,在這種情況下,p1
和p2
不能被聲明爲const
,因爲key()
方法修改其各自的對象。代碼編譯但這是一件壞事?
並使'key()'方法'const'。 – juanchopanza
是的 - 像這樣懶惰的一代(接下來是緩存)是少數情況下可變的真正有意義的事情之一。 –
完美!作爲C++的新手,我還沒有遇到過這種語言功能。很棒。 – jasonm76