Huy Nhat Tran
Huy Nhat Tran

Reputation: 145

Why range based for loop doesn't work with iterator, which points to container?

I have this code and it doesn't compile. It has an error:

cannot assign to variable 'value' with const-qualified type 'const int &'
value = 5;

#include <vector>
#include <set>

int main() {
    std::vector<std::set<int>> data;
    for (auto it = data.begin(); it != data.end(); ++it) {
        auto& inner = *it;
        for (auto& value: inner) {
            value = 5;
        }
    }
    return 0;
}

I thought inner is std::set<int>& and value would be int& in this case. Could someone explain this case?

Upvotes: 2

Views: 91

Answers (0)

Related Questions