update item in a std::set

Hello,

I am trying to modify an item (an object) stored in a set.
I know its position in set, so I can retrieve it via iterators, in code:
1
2
3
4
5
6
7
8
#define I_TH 4 // I am retrieving the 5th element
class Foo{};

std::set<Foo> bar; 
// initialise bar with several Foo objects
auto to_be_updated = std::next(bar.begin(), I_TH);

// how do I update it???  

I tested this snippet and relieves the element I wish to update, but if I try to modify it the compiler complaints.

Any idea/workaround?

Thanks.
closed account (SECMoG1T)
AFAIK

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.

http://www.cplusplus.com/reference/set/set/


if you want to modify the stored elements you should consider a different container or make a copy of the desired element onto which you can make changes as you want.
Last edited on
1
2
3
auto node = bar.extract(to_be_updated);
node.value() = new_value;
bar.insert(std::move(node));

https://en.cppreference.com/w/cpp/container/set/extract
Is the state being modified in the Foo object comparision-salient? If not, you can mark that state mutable.
Last edited on
extraction and reinsertion worked fine for me.
Thanks all for the clarification!
Topic archived. No new replies allowed.