奇怪的错误,set::begin() 总是返回 const 迭代器

发布于 2024-09-29 15:10:28 字数 346 浏览 0 评论 0原文

为什么 set.begin() 总是返回一个 const 迭代器而不是标准迭代器?

35 int test(){
36     std::set<int> myset;
37     myset.insert(2);
38     myset.insert(3);
39     int &res = *myset.begin();
40     return res;
41 }


test.cpp:39: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’

Why is set.begin() always returning a const iterator and not a standard one?

35 int test(){
36     std::set<int> myset;
37     myset.insert(2);
38     myset.insert(3);
39     int &res = *myset.begin();
40     return res;
41 }


test.cpp:39: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白芷 2024-10-06 15:10:28

它不返回 const_iterator,而是 std::set的 key_type 是 const int。

请记住,std::set 中的键是常量。密钥插入密钥组后就无法更改。因此,当您取消引用迭代器时,它必然返回一个常量引用。所以你需要说:

const int &res = *myset.begin();

It's not returning a const_iterator, rather the key_type of std::set<int> is const int.

Remember that keys in a std::set are constant. You can't change a key after it's inserted into the set. So when you dereference the iterator, it necessarily returns a constant reference. So you need to say:

const int &res = *myset.begin();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文