1

I get a compilation error with the following code:

#include <set>
#include <string>
using namespace std;

struct string_with_set_of_strings
{
    string str;
    set< string > strs;

    string_with_set_of_strings(string s) : str(s) {}

    bool operator < (const string_with_set_of_strings & swsos) const { return str < swsos.str; }
};

int main()
{
    set< string_with_set_of_strings > A;

    pair< set< string_with_set_of_strings >::iterator, bool> it = A.insert(string_with_set_of_strings("foo"));

    if (!it.second)
        it.first->strs.insert("goo");

    return 0;
}

Here is the error message (from Visual Studio 2017):

error C2663 : 'std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>::insert' : 5 overloads have no legal conversion for 'this' pointer
    with
    [
        _Kty = std::string,
        _Pr = std::less<std::string>,
        _Alloc = std::allocator<std::string>
    ]

It's referring to the line where I try to insert "goo". I realize that it.second would equal true since the first insertion into A would succeed, so the "goo" line wouldn't even be encountered during runtime, but that doesn't explain the compiler error. I don't know why the second insertion isn't accepted by the compiler. Any help appreciated.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Marc Nye
  • 124
  • 6

1 Answers1

1

You cannot modify an element of a set, thus the error.

In other words, the elements of an std::set are const, thus immutable.

Moreover, when compiling, the error should state something like this:

note:   passing 'const std::set<std::__cxx11::basic_string<char> >*'
        as 'this' argument discards qualifiers

Read more in what happens when you modify an element of an std::set?

gsamaras
  • 71,951
  • 46
  • 188
  • 305