Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update a member in a set of std::pair? [duplicate]

I tried doing this:

std::set< pair<int, int> > mySet;

// fill the set with something

mySet.find( make_pair(someValueX, someValueY) )->first = newX;

But I get the following error on compilation:

error: assignment of member 'std::pair<int, int>::first' in read-only object|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===||
like image 729
Tudor Versoiu Avatar asked Mar 01 '17 17:03

Tudor Versoiu


People also ask

Can you update a pair in C++?

You can't, you need to remove the pair and insert the new one. This has nothing to do with std::pair , it's a limitation imposed by std::set .

How do you modify a pair in C++?

To modify them, one can only delete and add components. C++ pair is a type that is specified under the utility> header and is used to connect two pair values. The pair's values can be of separate or identical types. To view the values in a pair independently, the class has the member functions first() and second().

What happens when we insert duplicate values in set C++?

In Set duplicate values are not allowed to get stored. On other hand in case of MultiSet we can store duplicate values. In case of Set, one cannot change the value once it gets inserted however we can delete or insert it again. However in case of MultiSet also we cannot change the value once get inserted.


1 Answers

Members of std::set are const, because changing them could make their ordering invalid. You would have to erase the pair and re-insert it after it was changed.

like image 78
alain Avatar answered Oct 03 '22 21:10

alain