Click to See Complete Forum and Search --> : Pointers, STL....Help


Ham266
January 31st, 2005, 07:39 PM
Hi !,
Any help here would be greatly appreciated. What I have is a STL vector, named "people", that has been populated with my own user defined Class "Person".

I now wish to create an array of pointers, named "firstGroup", to a select few elements within the STL vector. With the last person to be specified by name


void Group::selectGroup()
{
for(int i = 0 ; i < 10 ; i++)
{
firstGroup[i] = &people[i];
}

firstGroup[9] = getPerson("Fred"); // ERROR OCCURS HERE
}


Person* Group::getPerson(string surname)
{
vector<Person>::iterator it;
for(it = people.begin(); it != people.end(); it++)
{
if(it->getName() == surname)
{
return it;
}
}
return NULL;
}


This all compiles OK except there is a segmentation fault when I include the line where the error occurs. I figure it must be the getPerson method but where?

thanks
ham

HighCommander4
January 31st, 2005, 08:45 PM
A vector<Person>::iterator is not necessarily a pointer-to-Person. The designers of the STL could have chosen to implement it in any way they liked, such as using a class.

So in your getPerson() function, instead of

return it; // returns a vector<Person>::iterator

you should have

return &(*it); // returns a Person*

If that doesn't help, you'll need to post your entire code so we can see what the Person class looks like and how you are using these functions in a program.

Andreas Masur
February 1st, 2005, 06:22 AM
Besides that....are you doing the lookup very often? In this case I would rather suggest using a map instead...having the name as the key...thus, finding elements will be much faster...