CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2005
    Posts
    1

    Question 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

  2. #2
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    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

  3. #3
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    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
  •  





Click Here to Expand Forum to Full Width

Featured