c++ - read-only variable is not assignable问题
PHP中文网
PHP中文网 2017-04-17 14:25:34
[C++讨论组]

不知道该如何叙述这个问题,请看代码:

#include <set>
#include <iostream>
using namespace std;

struct test {
    int data[3];
};

int main(void) {
    test t1;
    set<test> s;
    s.insert(t1);
    s.begin()->data[0] = 1;//此处赋值报错:read-only variable is not assignable

    return 0;
}

应该是set内部的问题吧?
求高人解释,非常感谢...

PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
高洛峰

set内的元素不可以更改,只能增加或者删除。http://www.cplusplus.com/refe...

Sets are containers that store unique elements following a specific order.

In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. 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.

Internally, the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

set containers are generally slower than unordered_set containers to access inpidual elements by their key, but they allow the direct iteration on subsets based on their order.

Sets are typically implemented as binary search trees.
ringa_lee

意思好像是:只读的变量是不能被赋值的。。。

PHP中文网

set的迭代器是只读的,不允许修改(因为set内部有将元素排序,随意更改元素的值可能会破坏其有序性);

要改变元素的值,只能先把旧的删除,再把新的插入进去

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号