ravi
ravi

Reputation: 55

What's the issue using iterator here

i've just started with c++ stl and i'm unable to figure out the error...your help be greatly appreciated...

int count = 0 ;
while (!s.empty()) 
{
    s.erase(--s.end());
    set<int >::iterator it;
    for (it = s.begin(); it != s.end(); it++) 
    {

        if (*it > 0)
            * it -= r; //*error : expression must be modifiable lvalue
             //r is a constant
        else 
            s.erase(it);
    }
    count++;
}

cout << count;

Upvotes: 0

Views: 85

Answers (3)

Marshall Clow
Marshall Clow

Reputation: 16670

@Oblivion has the answer, but I would say it slightly differently.

A set is an ordered collection of elements. The order is maintained by the set. If you could change the elements of the set (via the iterator), then you would break the ordering of the elements in the set, so the iterators provided by the set give you only read access to the elements in the collection.

If you want to "change" the value of an entry in the set, you can erase the old one and insert a new (presumably different) one.

Upvotes: 0

Laiba Ijaz Khan
Laiba Ijaz Khan

Reputation: 115

If you have made an iterator Constant you can not modify its value. It's better that you change your variable type to a simple variable or create any new variable you wish to have. This might help you https://www.geeksforgeeks.org/how-to-modify-a-const-variable-in-c/

Upvotes: 1

Oblivion
Oblivion

Reputation: 7374

set's iterator is constant you cannot modify it.

The member types iterator and const_iterator may be aliases to the same type. This means defining a pair of function overloads using the two types as parameter types may violate the One Definition Rule. Since iterator is convertible to const_iterator, a single function with a const_iterator as parameter type will work instead.

The elements are constant too you cannot modify them anyhow.

A solution to your problem would be to erase the element you wish to modify and insert the new element you wish to have.

Upvotes: 1

Related Questions