【发布时间】:2016-05-08 06:52:29
【问题描述】:
从不改变其对象状态的函数中使用 std::map 时注意到一种特殊行为:
std::map<std::string, int> _attribLocations;
...
int ProgramInfo::getAttribLocation(const std::string& name) const
{
return _attribLocations.at(name);
}
当我调用这个函数时,传递一个字符串文字,查找抛出 out_of_range 异常:
auto index = info.getAttribLocation("v_position");
我注意到 at() 有两个版本,一个使用 const_iterator,一个不使用:
mapped_type& at(const key_type& _Keyval)
{ // find element matching _Keyval
iterator _Where = _Mybase::lower_bound(_Keyval);
if (_Where == _Mybase::end()
|| _Mybase::_Getcomp()(_Keyval, _Mybase::_Key(_Where._Mynode())))
_Xout_of_range("invalid map<K, T> key");
return (_Where->second);
}
const mapped_type& at(const key_type& _Keyval) const
{ // find element matching _Keyval
const_iterator _Where = _Mybase::lower_bound(_Keyval);
if (_Where == _Mybase::end()
|| _Mybase::_Getcomp()(_Keyval, _Mybase::_Key(_Where._Mynode())))
_Xout_of_range("invalid map<K, T> key");
return (_Where->second);
}
};
似乎导致它抛出的部分是:
_Mybase::_Getcomp()(_Keyval, _Mybase::_Key(_Where._Mynode()))
我并没有真正调试过比这更深的东西。
我正在使用 Visual Studio 2015。
我确信正在传递的密钥确实存在于地图中(通过使用调试器检查地图)。可能是地图实现中的错误,或者我错过了比较字符串的一些内容?
【问题讨论】:
-
我正在使用 VS2015 Update 2,无法重现此行为。您是否尝试过在一个最小的示例项目中重现它?
-
你必须告诉我们MCVE。
-
没关系,我很笨。
标签: c++ string c++11 constants stdmap