How to change a set element?

后端 未结 3 669
死守一世寂寞
死守一世寂寞 2020-11-27 22:44

I want to change the element in a set, so I used set::iterator. However, the compiler argues \"the element is const\". Then I realized tha

相关标签:
3条回答
  • 2020-11-27 23:31

    Set elements are constant and may not be modified in place. Modification could change the ordering predicate without changing the position of the element which would violate the constraints of the data structure.

    However now in the future (C++17), modifying the element without erasure is possible with the extract member function:

    std::set<std::string> stringset{"a", "b", "c"};
    auto node = stringset.extract(stringset.begin());
    std::string& str = node.value();
    str = "d";
    stringset.insert(std::move(node));
    

    There is still the cost of list operations but the object itself is not destroyed or copied.

    0 讨论(0)
  • 2020-11-27 23:36

    The elements of the set will be in sorted order. If you are allowed to modify an element, then this sorting order can not be maintained. Hence you can not modify the item. You need to erase the existing element and insert a new one.

    0 讨论(0)
  • 2020-11-27 23:37

    EDIT: You cant add an element to a specific location in set. the set should be in the sorted order whatever operations you do. So you have to erase the specific element and insert the new element so that the ordering of set isnt lost.

    Also read more about set!

    0 讨论(0)
提交回复
热议问题