Hi every one I'm new to C++, and practicing it by leetcode. Today when I was trying lc127, this error confused me. This error comes from one ranged for statement, where variable first is of the type unordered_set. And if I removed the reference mark&, then it works all right. The most minimal reproducible example is like:
unordered_set<string> first{ beginWord }, last{ endWord };
int i = 0, j = 'a';
for (auto& word : first) {
word[i] = j;//error here
}
And the error shows:
Line 17: Char 33: error: cannot assign to return value because function 'operator[]' returns a const value
word[i] = j;
~~~~~~~ ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:1045:7: note: function 'operator[]' which returns const-qualified type 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>::const_reference' (aka 'const char &') declared here
const_reference
^~~~~~~~~~~~~~~
My question is that why the former version is wrong? To my understanding, if I want to change the value in a ranged for statement, then I should use a & to ensure that I changed the value?
Full code link:Full code is here Thank you in advance!