Changing a class member through an iterator

I am learning C ++ and cannot solve this problem:

I have a simple class A

class A { private: int ival; float fval; public: A(int i = 0, float f = 0.0) : ival(i), fval(f) { } ~A(){ } void show() const { cout << ival << " : " << fval << "\n"; } void setVal(int i) { ival = i; } //const getters for both ival and fval //used for the default "lesser" friend bool operator<(const A& val1, const A& val2) { return val1.ival < val2.ival ? true : false;; } } 

Then I have a regular set<A> myset , which is populated with insert(A(2, 2.2)); in a loop.

An iteration to get all values โ€‹โ€‹is not a problem, but I want to change the value in this iteration:

 for(set<A>::iterator iter = set3.begin(); iter != set3.end(); iter++) { iter->setVal(1); } 

I suppose this should be doable, as you would do it in Java in a foreach loop. When compiling, I get error: passing 'const A' as 'this' argument of 'void A::setVal(int)' discards qualifiers .

Looking at the sources of the STL collection, I can see that begin() is only available as a const method, and I think this might be a problem. The mess with a constant in the setVal() method always got the same error and doesn't make much sense since I want to change the value of A

Is this the wrong approach to changing the set of values โ€‹โ€‹of A using a loop?

+4
source share
2 answers

The STL set does not allow changing the values โ€‹โ€‹that it stores. It does this by returning a copy of the object through an iterator (rather than the actual one in the set).

The reason this is set up is because it uses <to order a set, and it doesnโ€™t want to redo the whole tree every time you look for an iterator, which it will have to do, because it doesnโ€™t know if you changed something- or that will change the order.

If you need to update the set <>, delete the old value and add a new one.

EDIT: Just checked the source on SGI STL and it says the following:

  typedef typename _Rep_type::const_iterator iterator; 

So set :: iterator is just set :: const_iterator

+5
source

From this page , it seems that begin() exists, as well as the non-const method.

Perhaps your set was passed to the method as a reference to a constant?

EDIT

The link to the page is incorrect. According to Sharron, there is no t20> (or end() ) method for ordered containers.

I will report the website about their error (these are not the first they made;))

+1
source

All Articles