rubenvb
rubenvb

Reputation: 76519

Initializing a std::map iterator class member

I'm trying to do this:

typedef std::map<std::string, time_t> my_map;
const mymap& some_function();

class bla
{
private:
  my_map::iterator current
  bla(const mymap& m) : current(m.begin())
  {   }
}

And it's not working. The somewhat more convoluted real error message is:

error: no matching function for call to 'std::_Rb_tree_iterator, long int> >::_Rb_tree_iterator(std::map, long int>::const_iterator)'

I tried moving the initialization/assignment to the constructor body:

{ current = m.begin(); }

Which didn't work either. So I thought, the type of current is wrong, so I just let the compiler deduce that:

...
   decltype(my_map::begin()) current;
...

Which doesn't work either.

All I need is an iterator member that is set at bla construction time, so I don't have to explicitly set it in some stupid extra function and can iterate over the map externally through:

bool bla::do_stuff(...output...)
{ 
    if(current = m.end())
        return false;
    balblabla(current);
    ++current;
    return true;
}

Upvotes: 3

Views: 2594

Answers (2)

Cat Plus Plus
Cat Plus Plus

Reputation: 129774

You're trying to assign const_iterator to iterator. There are two solutions:

  1. Take map by non-const reference (bla(my_map& m) : current(m.begin()) {}).
  2. Change the member type to const_iterator.

Upvotes: 6

Kerrek SB
Kerrek SB

Reputation: 476980

In a const context, you can only obtain a const_iterator:

my_map::const_iterator current;
bla(const my_map & m) : current(m.begin()) { }

If you want a non-const iterator, you have to construct your bla object from a non-constant reference.

Upvotes: 4

Related Questions