user1873947
user1873947

Reputation: 1811

Are pointers stored in std::set const?

I'm hunting a bug in code and I have a problem:

 class a
 {
 public:
 void foo(int a) {}
 }

  std::set<a*> set;
  std::set<a*>::iterator it = set.begin();

  it->foo(55); //gives me error:
  // error: request for member ‘foo’ in ‘* it.std::_Rb_tree_const_iterator<_Tp>::operator-><a*>()’, which is of pointer type ‘a* const’ (maybe you meant to use ‘->’ ?)

Why it doesn't allow me to use non-const function on it? What can I do to have a set of non-const pointers without using casting?

Upvotes: 0

Views: 934

Answers (3)

andre
andre

Reputation: 7249

The issue is you need to deference the iterator and then the pointer. replace it->foo(55); with (*it)->foo(55); This will work.

Upvotes: 3

Grimm The Opiner
Grimm The Opiner

Reputation: 1806

You're one level of indirection out.

(*it)->foo(55);

works, as it is effectively a pointer to the type stored, which is itself a pointer.

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

You need to dereference twice:

(*it)->foo(55);

it is an iterator to a pointer. Your code would be correct if you had an std::set<a> instead of an std::set<a*>.

Upvotes: 9

Related Questions