|
-
January 31st, 2005, 08:39 PM
#1
Pointers, STL....Help
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
-
January 31st, 2005, 09:45 PM
#2
Re: Pointers, STL....Help
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
Code:
return it; // returns a vector<Person>::iterator
you should have
Code:
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.
Old Unix programmers never die, they just mv to /dev/null
-
February 1st, 2005, 07:22 AM
#3
Re: Pointers, STL....Help
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...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|