gpt4 book ai didi

c++ - 我可以将具有非常量值类型的映射转换为具有常量值类型的映射吗?

转载 作者:搜寻专家 更新时间:2023-10-31 01:10:13 29 4
gpt4 key购买 nike

我有如下内容:

map<int, StructType> map;
const map<int, StructType>& GetMap() { return map; }

我想按照这些思路做一些事情:

const map<int, const StructType>& GetConstMap() { return map; }

有什么方法可以将这个const-ness 添加到映射的值类型中吗?

最佳答案

std::map的界面被设计成const map<K,T>通过从不公开对其元素的非常量访问,有效地具有 const 值类型。

因此您不能通过 const map 添加、删除或修改元素引用。

所以:

struct X
{
map<int, StructType> m;

const map<int, StructType>& GetConstMap() const { return m; }
}

就是你想要的。

关于c++ - 我可以将具有非常量值类型的映射转换为具有常量值类型的映射吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155585/

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