修改 std::map 的键 [英] Modify key of std::map
本文介绍了修改 std::map 的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法修改 std::map
或 ?这个例子 显示了如何通过重新平衡树来做到这一点.但是,如果我提供一些密钥不需要重新平衡的保证怎么办?
Is there a way to modify the key of a std::map
or ? This example shows how to do so with rebalancing the tree. But what if I provide some guarantees that the key won't need to be rebalanced?
#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
有什么办法可以覆盖这种行为吗?
Is there any way to override this behavior?
推荐答案
You can make inc
const and total
mutable
You could make inc
const and total
mutable
class Keymap
{
private:
int key; // this key will be used for the indexing
mutable int total;
public:
Keymap(int key): key(key), total(0)
{}
bool operator<(const Keymap& rhs) const{
return key < rhs.key;
}
void inc() const
{
total++;
}
};
但是你确实需要问问自己为什么要这样做,mutable
用得不多.
But you do need to ask yourself why you are doing this, mutable
isn't used much.
您说得对,不会发生再平衡.
You're right that no rebalancing is going to happen.
这篇关于修改 std::map 的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文