Use iterator to call the non-static function in ST

2019-08-05 10:28发布

问题:

In the following program, I have a class A with a non-static function void add(). I want use the iterator to call add() for each element in the set, but there is a error at the last element.

How can I fix it?

#include <iostream>
#include <set>

using namespace std;

class A
{
private:
    int a;
public:
    A(int x) { a = x; }
    void add() {a = a + 1; }
    bool operator<(A x) const { return a < x.a; }
};

int main()
{
    //type of the collection
    typedef set<A> IntSet;

    //define a IntSet type collection
    IntSet col1;
    IntSet::iterator pos;

    //insert some elements in arbitrary order
    col1.insert(A(3));
    col1.insert(A(4));
    col1.insert(A(5));

    //iterator over the collection and print all elements

    for(pos = col1.begin(); pos != col1.end(); ++pos)
    {
        (*pos).add();
        // ERROR!: Member function 'add' not viable:
        // 'this' argument has type'const value_type' 
        // (aka 'const A'), but function is not marked const
    }
    cout << endl;
}

回答1:

Items contained in a set<> container are considered const and cannot be modified. If they did, their identity might change but set<> wouldn't be aware of this, wreaking havoc on its internal structure as an item would be stored in a bucket where it didn't belong!

Consider, for example, that set<> uses your custom operator< overload in order to sort its contents. What would you expect to happen if you change the a member variable while the object is contained in a set? The set won't know that a changed and will leave the object where it was.

To fix this potential problem, set<> only gives you references to const instances of contained objects.

You will only be able to use const members of your class in this context, and add() is not declared const. If you want to modify the object and have those changes reflected in the set, you will have to make a copy of the object, remove the original object from the set, make the change to your copy, and then add the copy to the set.



标签: c++ stl set