首頁  >  問答  >  主體

c++ - read-only variable is not assignable问题

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

#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中文网2765 天前875

全部回覆(3)我來回復

  • 高洛峰

    高洛峰2017-04-17 14:27:34

    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.

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-17 14:27:34

    意思好像是:只讀的變數是不能被賦值的。 。 。

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-17 14:27:34

    set的迭代器是唯讀的,不允許修改(因為set內部有將元素排序,隨意更改元素的值可能會破壞其有序性);

    要改變元素的值,只能先把舊的刪除,再把新的插入進去

    回覆
    0
  • 取消回覆