Gio
Gio

Reputation: 4229

Do STL iterators return const objects?

It's been a long time since we used STL so anyhelp would be appreciated. Not sure what we're doing wrong here... Given this, why does this code throw an error:
"you cannot assign to a variable that is const"

struct person
{
int age;
bool verified;
string name

bool operator< (person const &p)
{
return (age < p.age);
}

};

multiset<person> msPerson;
multiset<person>::iterator pIt;

// add some persons
while (adding people)
{
    Person p;
    p.name=getNextName();
    p.age=getNextAge();
    msPerson.insert(p);
}


pIt = msPerson.begin();
// try to verify
pIt->verified = true; <---- **error here....**

Upvotes: 2

Views: 548

Answers (3)

32bits
32bits

Reputation: 710

sets return read-only iterators. Other containers in stl do not (e.g. vector).

Upvotes: 1

Charles Brunet
Charles Brunet

Reputation: 23120

You should use

(*pIt).verified = true;

-> operator isn't defined for STL iterators.

Upvotes: -1

Jay
Jay

Reputation: 14461

They return a const iterator if the container is ordered. The idea is that if you change the content the container doesn't know and it cannot guarantee order. Vector does not, but map does.

If you're sure your update does not affect the sort order you can cast away the const-ness. As always proceed with caution if you do that.

Upvotes: 2

Related Questions