C++ 不能分配给返回值,因为函数“operator []”返回一个 const 值

问题描述

大家好,我是 C++ 新手,正在通过 leetcode 练习。 今天当我尝试 lc127 时,这个错误让我很困惑。此错误来自一个 ranged for 语句,其中变量 first 的类型为 unordered_set。如果我删除了参考标记&,那么它就可以正常工作。 最小的可重现示例如下:

            unordered_set<string> first{ beginWord },last{ endWord };
            int i = 0,j = 'a';   
            for (auto& word : first) {
            word[i] = j;//error here
            }

错误显示

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
      ^~~~~~~~~~~~~~~

我的问题是为什么以前的版本是错误的?据我了解,如果我想更改 ranged for 语句中的值,那么我应该使用 & 来确保我更改了该值?

完整代码链接Full code is here 提前致谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)