通过const函数中的参数索引返回std :: map的值

Returning a value of std::map via param index within a const function

本文关键字:std 返回 map 的值 索引 参数 const 函数 通过      更新时间:2023-10-16

有没有办法将std :: map索引作为const函数上的参数?

const SurfaceProperties &  SurfacePropertiesImpl::getSurfaceProperties(const std::string entityId) const
{
    return mSurfaceProperties[entityId];
}

-

 error: passing ‘const std::map<std::__cxx11::basic_string<char>, SurfaceProperties>’ as ‘this’ argument discards qualifiers [-fpermissive]
     return mSurfaceProperties[entityId];

您可以使用与operator[]

相反的at
const SurfaceProperties&
SurfacePropertiesImpl::getSurfaceProperties(const std::string entityId) const
{
    return mSurfaceProperties.at(entityId);
}

如果找不到键,它将投掷。