gpt4 book ai didi

c++ - 处理 map 键中指向值的常量

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

我有以下代码:

#include <map>
using namespace std;
struct A {};

map</*const*/ A *, int> data;

int get_attached_value(const A *p) {
return data.at(p);
}
void reset_all() {
for (const auto &p : data) *p.first = A();
}

我的问题是,当我在 data 类型中注释和取消注释 const 时,此代码因类型错误而失败。有什么方法可以在不使用 const_cast 并且不丢失 get_attached_value 中的 const 的情况下解决这个问题?

最佳答案

问题似乎出在pointee 类型,这在两个指针声明中必须相同(映射键类型和get_attached_value 的参数)。

OP 的代码使用 const A*,它是指向 A 类的 const 实例 的指针(另一种拼写是 A const * ).在 map 声明和 get_attached_value 参数中保留此 const 几乎可以工作,但 reset_all 不允许您将新值分配给 *p.first,因为结果类型是 A const&(无法赋值)。

删除两个常量也可以,但 OP 希望在 get_attached_value 中保留一个常量。

为了满足 OP 的要求,保留尽可能多的 const 的一种解决方案似乎是将指针类型更改为 const 指针,指向 A 的非 const 实例。这将使 reset_all 继续工作,同时允许在 map 声明和 get_attached_value 的参数中使用 const 指针:

#include <map>
using namespace std;
struct A {};

map<A * const, int> data;

int get_attached_value(A * const p) {
return data.at(p);
}
void reset_all() {
for (const auto &p : data)
*p.first = A();
}

另一种可能的解决方案是将 map 的键作为非常量,但 get_attached_value 的参数为常量,可以使用带有自定义比较器的 std::lower_bound 来替换 data.at()调用:

#include <map>
#include <algorithm>

using namespace std;
struct A {};

map<A*, int> data;

int get_attached_value(A const * const p) {
auto it = std::lower_bound(data.begin(), data.end(), p,
[] (const std::pair<A* const, int>& a, A const* const b) {
return a.first < b;
}
);
return it->second;
}
void reset_all() {
for (const auto &p : data)
*p.first = A();
}

但是,与使用 map 的 native 搜索功能的解决方案相比,此解决方案的效率要低得多 - std::lower_bound uses linear search when input iterators are not random access .

总而言之,C++11 或更低版本中最有效的解决方案可能是使用 const 指针作为映射的键,并在 reset_all 函数中使用 const_cast

可以找到更多关于 const 符号和指针的阅读 here .

关于c++ - 处理 map 键中指向值的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29066432/

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