Hi,


I have a program, which uses a vector to store some pointers.

The program works fine.

I'm trying to convert it to use a doubly linked list now though.

At the top of the program I changed:

vector<Diary *>vectorname;

to

#include <list>

list<Diary *>vectorname;

list<Diary*>::iterator i = vectorname.begin();

Later on in the program I access an element of the (former) vector using:

if(vectorname[a]->getName() == leadToDelete)

And use:

if(advance(i,a)->getName() == leadToDelete)
{
      //do something
}

instead.

BUt when I try it fails to compile, saying:

error C2227: left of '->getName' must point to class/struct/union/generic type

I was hoping this would be a simple way to do the conversion, but I have made a mistake in the code above it seems.

Could anyone show me how I do this?

Many thanks for any help!

Recommended Answers

All 3 Replies

The trouble is that advance does not return an iterator, AND the iterator
(i in your code), has to be double derefrenced because the iterator points to a pointer and hence the error message. You need:

advance(i,a);
if ( (*i)->getName()==someVar )
{
}

Note I have added the extra brackets for clarity.

HOWEVER : if you have lots of calls to the advance method you really would be better off with a vector, but you can obviously test the runtime performance.

commented: Thanks buddy! :) +1

Thanks StuXYZ !

Works great, almost got it compiling now, but how would I convert:

vectorname.erase(vectorname.begin() + a);

To use your solution?

The problem you have is that your are using bare pointers. If you were using boost::shared_ptr or even std::auto_ptr then no problem.

So how to delete. You need to do TWO things: (a) delete the memory that the pointer points to, (b) delete the reference.

If you are deleting only one reference then that is easy.

Assuming that you are using vectors:

std::vector<Diary*> V;
std::vector<Diary*>::iterator  Ivec;
//
// Ivec get set / V gets filled etc.
// ...
delete *Ivec;
V.erase(Ivec); 
// NOTE : Ivec NOT not valid:

You can use the return of vector.erase to give you the next valid iterator. You would do that if you are looping through the vector and deciding which to delete . e.g.

std::vector<int> XV;  
  for(int i=0;i<10;i++)
      XV.push_back(i);

  std::vector<int>::iterator xvIter=XV.begin();
  while(xvIter!=XV.end())
    {
      if ((*xvIter%2))
	xvIter=XV.erase(xvIter);
      else
	xvIter++;
    }
  
  copy(XV.begin(),XV.end(),std::ostream_iterator<int>(std::cout," : "));
  std::cout<<std::endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.