Returning a pointer to a vector element in c++

Krakkos picture Krakkos · Mar 13, 2009 · Viewed 112.1k times · Source

I have a vector of myObjects in global scope. I have a method which uses a std::vector<myObject>::const_iterator to traverse the vector, and doing some comparisons to find a specific element. Once I have found the required element, I want to be able to return a pointer to it (the vector exists in global scope).

If I return &iterator, am I returning the address of the iterator or the address of what the iterator is pointing to?

Do I need to cast the const_iterator back to a myObject, then return the address of that?

Answer

anon picture anon · Mar 13, 2009

Return the address of the thing pointed to by the iterator:

&(*iterator)

Edit: To clear up some confusion:

vector <int> vec;          // a global vector of ints

void f() {
   vec.push_back( 1 );    // add to the global vector
   vector <int>::iterator it = vec.begin();
   * it = 2;              // change what was 1 to 2
   int * p = &(*it);      // get pointer to first element
   * p = 3;               // change what was 2 to 3
}

No need for vectors of pointers or dynamic allocation.