我想在C++中存储具有自定义比较器功能的对象std::map,例如:
std::map<Part, Inventory, PartCmp>
Run Code Online (Sandbox Code Playgroud)
对于比较器,我想通过一个计算成本昂贵的"密钥"对对象进行排序,所以我想到了一种懒惰的评估方法.下面的例子有点微不足道,但说明了问题:
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_;
}
Run Code Online (Sandbox Code Playgroud)
这意味着我的比较器看起来像:
struct PartCmp {
bool operator() (Part& p1, Part& p2) const {
return p1.key() < p2.key();
}
};
Run Code Online (Sandbox Code Playgroud)
这与我见过的所有其他示例不同,p1并且p2被声明为const参数.
但是,在这种情况下p1并p2不能声明为const自key()方法修改其各自的对象.代码编译但这是一件坏事吗?
您可能想要声明该字段
private:
mutable std::string key_;
Run Code Online (Sandbox Code Playgroud)
看到这个问题.
而且,正如juanchopanza的评论所建议的那样,制定你的key()方法const
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |