Reputation: 27
I have a set of sets of ints called nets which I'm trying to iterate through to determine if either of the ints to or from have been added to an existing set; if so, I add them to the existing set (this is to keep track of all combinations of shorts on an electrical network).
However, I CANNOT get the set::insert function to work! I'm able to use (*it).count just fine to determine if either int has already been added to a set, but (*it).insert doesn't work (I always receive the error No matching member function call to 'insert'). However, if I just create a set of ints, setName.insert(to) works fine.
What's wrong with my code?
for (std::set<std::set<int>>::iterator it=nets.begin(); it!=nets.end(); ++it) {
if ((*it).count(to) || (*it).count(from)) {
currentSet = (*it);
(*it).insert(to);
(*it).insert(from);
addedToExistingSet = true;
}
}
Upvotes: 0
Views: 1399
Reputation: 14510
As a std::set
is an associative container that contains a sorted set of unique objects of type T
, you cannot modify an object inside it because you would invalidate the set
.
If it was allowed, you'd be allowed to change the items value out from under the container, potentially altering the ordering.
The standard says :
23.2.4 Associative containers [associative.reqmts]
iterator
of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, bothiterator
andconst_iterator
are constant iterators.
You should consider using another container for the outer one like std::vector
.
Upvotes: 2
Reputation: 2713
The problem here is that you are trying to modify an object inside a set, which isn't a valid operation as you would invalidate the set. Is there a reason you need the outer container to be a set? Could it be a std::vector
for example?
Upvotes: 0