I would like to mutate 'out' by roughly something like this:
set<list<int>> out = {{1, 2, 3}, {6, 7, 8}};
for (auto &it : out)
{
it.push_front(2);
}
Code above will compile with error:
passing ‘const std::__cxx11::list’ as ‘this’ argument discards qualifiers [-fpermissive] it.push_front(2);
I vaguely get that this case can possibly discard some const qualifier. Is there a way to work around it or should I follow some different approach?
When inserting something into a set, it is placed into a red-black tree to represent sort order and help with unique value insertion. Changing a value after insertion would break the sets core functionality.
Set iterators in C++ docs have the note
https://en.cppreference.com/w/cpp/container/set/begin
Because both iterator and const_iterator are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions.
That also means you could change them by other means but it is not a good idea.
The list container does not have such limitations and is the right choice here in my opinion.
https://en.cppreference.com/w/cpp/container/list/begin
#include <list>
#include <iostream>
int main()
{
std::list<std::list<int>> listOfLists = {{1, 2, 3}, {6, 7, 8}};
for (auto& containedList : listOfLists)
{
containedList.push_front(2);
}
for (auto& containedList : listOfLists)
{
std::cout << "[";
for (auto& listItem : containedList) {
std::cout << listItem;
}
std::cout << "]" << std::endl;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With