1

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!

ホムリ
  • 11
  • 3
  • Please edit your code into the question as text along with any errors you're receiving. – Retired Ninja May 30 '21 at 03:21
  • @RetiredNinja Thanks for your comment. I have already modified it. – ホムリ May 30 '21 at 03:31
  • Elements in an `unordered_set` are const because of the way the container works. If you were able to modify them it would invalidate the hash. – Retired Ninja May 30 '21 at 03:42
  • "And if I removed the reference mark&, then it works all right. " Then you're copying the elements, so the modification works on a local copy. The set itself is unchanged. – L. F. May 30 '21 at 03:45
  • The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container. Source: https://www.cplusplus.com/reference/set/set/ Same applies for unordered_set – Sankalp Kotewar May 30 '21 at 03:51

0 Answers0