[英]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.