2

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Huy Nhat Tran
  • 135
  • 11
  • 5
    The data of a set is considered to be a *key*, much like the key of a map. And it's not possible to modify the keys. For one thing it would be bad for the ordered nature of `std::set`. – Some programmer dude Dec 27 '22 at 03:53
  • What would setting every element of a set to 5 mean if it worked? How many elements would the set then have? – Davis Herring Dec 27 '22 at 03:54
  • I tried your code, and it reproduced the error as-is (even the headers are included!). This much is good. However, improvement is possible -- your code could be more focused. As a next step, I eliminated the vector. `#include int main() { std::set data; for (auto& value: data) { value = 5; } return 0; }` -- I got the same error. It looks like "with iterator, which points to container" (from the title) is a red herring. *(I consider this "next step" to be a good thing to strive for, but I'll stop short of* expecting *it to be done.)* – JaMiT Dec 27 '22 at 06:25
  • Iterator to element in `std::set` is immutable so it will produce the same error. You can check `Note` section https://en.cppreference.com/w/cpp/container/set/begin @JaMiT – Huy Nhat Tran Dec 27 '22 at 06:52
  • @HuyNhatTran *"You can check Note section en.cppreference.com/w/cpp/container/set/begin JaMiT"* -- Thanks, but I already know both that the elements of a `std::set` are immutable and that cppreference.com is a good C++ reference. You seem to be under the misunderstanding that I am looking for an answer. I am not. I am looking to help you improve your questions to the next level. – JaMiT Dec 27 '22 at 07:54
  • 1
    Does this answer your question? [Const references when dereferencing iterator on set, starting from Visual Studio 2010](https://stackoverflow.com/questions/2523139/). Related: [no known conversion from 'const value_type' to 'const void *' for 1st argument](https://stackoverflow.com/questions/48285661/) – JaMiT Jan 04 '23 at 13:17

0 Answers0