在下面的程序中,我有一个A
带有非静态函数的类void add()
。我想使用迭代器来调用add()
集合中的每个元素,但是最后一个元素有错误。
我该如何解决?
#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;
}