微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。