Pierre
Pierre

Reputation: 1174

Return a reference on a string using an iterator

I have a vector containing strings, an iterator (_it) on this vector, and I would like to return a reference on one of the string using this iterator.

For now, the return is made by copy:

std::string myClass::next_token()
{
  std::vector<std::string>::const_iterator old_it = _it++;
  return *old_it;
}

I would like to do this (note the & on return-type)

std::string& myClass::next_token() 
{
//...
}

But I get the following error :

invalid initialization of reference of type ‘std::string& {aka std::basic_string<char>&}’ from expression of type ‘const std::basic_string<char>’ std::string& token = *old_it;

Upvotes: 0

Views: 92

Answers (2)

NathanOliver
NathanOliver

Reputation: 180720

You cannot create a string& from a const string & as the const string & is not modifiable. The reason you are getting a const string & is that you are using a const_iterator. If you change you code to

std::string& myClass::next_token()
{
    std::vector<std::string>::iterator old_it = _it++;
    return *old_it;
}

Upvotes: 2

Alan Stokes
Alan Stokes

Reputation: 18974

A const_iterator will never get you a non-const reference; you need to either use a plain iterator or return a const string &.

Upvotes: 3

Related Questions