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;
}