简体   繁体   English

取消引用集合迭代器时,将“ string&”绑定到“ const string”时出错

[英]Error binding 'string&' to 'const string' when dereferencing a set iterator

I'm using C++11 and STL. 我正在使用C ++ 11和STL。 I have this piece of code: 我有这段代码:

std::set<std::string>::iterator it;
[...]
std::string &str = *it;

Compiler throws this error: 编译器抛出此错误:

error: binding reference of type 'std::__cxx11::string& {aka std::__cxx11::basic_string&}' to 'const std::__cxx11::basic_string' discards qualifiers 错误:将类型'std :: __ cxx11 :: string&{aka std :: __ cxx11 :: basic_string&}'的引用绑定到'const std :: __ cxx11 :: basic_string'会丢弃限定符

Why is it happening? 为什么会这样呢?

The keys in a set or map are const. 集合或映射中的键是const。 If they were not, the set would not be able to provide its guarantee that elements are weakly ordered on the key. 如果不是,则该集合将无法保证其元素在键上的排序是弱的。 ie the would become inexplicably unsorted when users mutated the keys. 也就是说,当用户更改密钥时,密钥将变得无法分类。

The std::set iterator dereferences to a key. std::set迭代器取消引用键。 Keys are (to reiterate) const. 键是(重申)const。

Mutable references cannot bind to const references (language-imposed rule). 可变引用不能绑定到const引用(强加语言的规则)。

Therefore, either: 因此,要么:

std::string const& str = *it;   // refer to the key

or 要么

std::string str = *it;          // take a copy of the key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM