有没有一种方法可以修改 std::map
或者的键?这个例子展示了如何通过重新平衡树来实现。但是,如果我能提供一些保证,说明键不需要重新平衡,那该怎么办呢?
#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>
这样的东西? - Calethstd :: set <Cars,SortByLicensePlate> carsToInspect;
,在处理它们后要更改检查日期。 您可以(可能应该)在此处使用std :: vector
,但是您明白了。 - Max Langhofstd::map<CarLicensePlate, Car>
或类似于boost::multi_index
的东西,后者作为索引容器,具有一致的数据修改支持。 - bobah