gpt4 book ai didi

c++ - 调整 const 映射键

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:25:01 25 4
gpt4 key购买 nike

我想将 STL map 与逻辑上不变的键一起使用(并且我使用 map 的代码确保永远不会违反键顺序)但实际上实现为变量。例如,

struct K { int ka, kb; };

struct my_less : std::less<K> {
bool operator()(const K& l, const K& r) const
{ return l.ka+l.kb < r.ka+r.kb; }
};

std::map<K, int, my_less> m;

// put something into m and now modify keys

K& k = *const_cast<K *>(&m.begin()->first);
k.ka++;
k.kb--; // I skip code for verifying logical key immutability for the sake of example simplification

它有效( map 排序没有被破坏)但它看起来很丑。有没有更好的选择?

使用指针进行额外的间接访问(指针变为常量而不使数据变为常量)是可能的,但它会产生开销(并增加不必要的复杂性)。

将可变键部分从键移动到值对我来说不是一个选项。

最佳答案

您不能巧妙地编辑 map 的键是有充分理由的——您真的不应该这样做!在您的情况下,它似乎不会破坏 map 排序,但这并不能保证! (想一想,如果将两个键修改为具有相同的 ka 和 kb 值会发生什么?)

执行此操作的正确方法是从 map 中删除该元素,然后使用新键重新插入它。

std::map<K, int, my_less> m;

// Push our starting object into the map
K key;
key.ka = 42;
key.kb = 123;

m[key] = 1234;

// Get the first element
auto iter = m.begin();

// make a new key
K key2;
key2 = iter->first;
key2.ka++;
key2.kb--;

int value = iter->second;

// remove old value
m.erase(iter);

// insert new value
m[key2] = value;

关于c++ - 调整 const 映射键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20607760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com