Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutating collections in colletion via iterators in C++

Tags:

c++

iterator

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?

like image 964
Mateusz Rudzki Avatar asked Oct 19 '25 01:10

Mateusz Rudzki


1 Answers

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;
}   
like image 180
Marcel Blanck Avatar answered Oct 21 '25 17:10

Marcel Blanck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!