【发布时间】:2018-08-10 11:03:32
【问题描述】:
有没有办法修改std::map 或的密钥? This example 展示了如何通过重新平衡树来做到这一点。但是,如果我提供一些不需要重新平衡密钥的保证呢?
#include <vector>
#include <iostream>
#include <map>
class Keymap
{
private:
int key; // this key will be used for the indexing
int total;
public:
Keymap(int key): key(key), total(0)
{}
bool operator<(const Keymap& rhs) const{
return key < rhs.key;
}
void inc()
{
total++;
}
};
std::map<Keymap, int> my_index;
int main (){
std::map<Keymap, int> my_index;
Keymap k(2);
my_index.insert(std::make_pair(k, 0));
auto it = my_index.begin();
it->first.inc(); // this won't rebalance the tree from my understanding
return 0;
}
由于it->first的常量,修改不会编译
有没有办法覆盖这种行为?
【问题讨论】:
-
你能举一个重要的实际例子吗?
-
你是绑定到容器类型
std::map<Keymap, int>,还是可以改用struct Value { int total; int index; }; std::map<int, Value>之类的东西? -
@bobah 在某些情况下,您可能希望在对象之间进行映射,其中键比文字映射键或具有类似属性的集合具有更多功能。更准确地说,它肯定可以有其他成员不影响其排序顺序并且应该可以修改。比如说,你得到一个
std::set<Cars, SortByLicensePlate> carsToInspect;,你想在处理完检查日期后更改检查日期。您可以(并且可能应该)在此处使用std::vector,但您明白了。 -
@MaxLanghof - 所有这些用例都是设计缺陷。在您的示例中,它应该是
std::map<CarLicensePlate, Car>或类似于boost::multi_index的东西,作为索引容器,它始终支持数据修改。 -
@bobah 你有一个有效的观点,这可以被视为设计缺陷。但是,您提出的建议要么必须将
CarLicensePlate移出Car类,要么具有内存效率低下的重复字段。所以这一切都归结为关键与对象的关系。但我明白你的意思,很难用这个来说明问题。就我而言,我想避免重构以存储一些元数据的成本。