Const pointers returned for non-const objects. Why?

From: Erik Jälevik (erik.jalevikDELETE_at_ntlworldTHIS.com)
Date: 01/31/04


Date: Sat, 31 Jan 2004 17:45:38 -0000

I've got lost in the STL template jungle again. I have some code that won't
compile and for the moment, I can't see why. Here's the gist of it:

std::map<std::string, unsigned int> genre2ID;

// ...

const vector<string*> MusicCollection::GetGenres() {

  vector<string*> v;
  map<string, unsigned int>::iterator it;
  for(it = genre2ID.begin(); it != genre2ID.end(); ++it) {
    v.push_back(&(it->first));
  }

  return v;

}

I simply want to iterate through the map and return a vector containing a
pointer to each string in the map. As strings are stored as objects in the
map, I take their address with &(it->first) before pushing them into the
vector.

However, for some reason the strings come out as const string* pointers from
this expression and the compiler tells me 'cannot convert from 'const
std::string *' to 'std::basic_string<_Elem,_Traits,_Ax>'.

I can get it to compile by making v a vector<const string*> but I don't see
why I should have to do that. Why do I get const pointers when the strings
in the map are not const?

Ever grateful for all the great help I get from this group.

Erik



Relevant Pages