[英]Error binding 'string&' to 'const string' when dereferencing a set iterator
我正在使用C ++ 11和STL。 我有这段代码:
std::set<std::string>::iterator it;
[...]
std::string &str = *it;
编译器抛出此错误:
错误:将类型'std :: __ cxx11 :: string&{aka std :: __ cxx11 :: basic_string&}'的引用绑定到'const std :: __ cxx11 :: basic_string'会丢弃限定符
为什么会这样呢?
集合或映射中的键是const。 如果不是,则该集合将无法保证其元素在键上的排序是弱的。 也就是说,当用户更改密钥时,密钥将变得无法分类。
std::set
迭代器取消引用键。 键是(重申)const。
可变引用不能绑定到const引用(强加语言的规则)。
因此,要么:
std::string const& str = *it; // refer to the key
要么
std::string str = *it; // take a copy of the key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.