gpt4 book ai didi

c++ - 更新 std::map 中键的值

转载 作者:IT老高 更新时间:2023-10-28 23:10:38 31 4
gpt4 key购买 nike

假设我们有一个简单的结构,如下所示

struct T{
int x;
int y;
};
T t1, t2;

还假设我有一个 map myMap 并且两个 T 类型的结构使用它们的 x 值进行比较只要。 IE。 t1 < t2 iff t1.x < t2.x。我正在尝试通过 myMap 更新键的一些 y 值。这不应该影响 map 如何看到键。除了删除旧元素并插入新元素之外,还有其他方法吗?

最佳答案

如果你确定 y 不参与你的类的“逻辑状态”并且仅仅是一个实现细节,那么你可以将它声明为 mutable:

struct T
{
int x;
mutable int y;
bool operator<(const T& rhs) const { return x < rhs.x; }
};

现在你应该可以改变y了:

for (auto it = m.begin(); it != m.end(); ++it)
{
it->first.y = -2; // ouch? But it won't invalidate the map's invariants.
}

关于c++ - 更新 std::map 中键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248078/

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