Thread: Vector/Pointer Help

  1. #1
    Registered User (TNT)'s Avatar
    Join Date
    Aug 2001
    Location
    UK
    Posts
    339

    Vector/Pointer Help

    Hi,

    If i have a pointer to a vector what is the correct syntax to access an element of the vector?

    For example:

    Code:
    void myfunc(std::vector<std::string> *p)
    {
    ...
    my_str = p[i]->mystring;
    ...
    }
    As expected this obviously fails, but whats the correct syntax for accessing an element at a position inside a vector?

    Thanks for any help,

    Jack
    TNT
    You Can Stop Me, But You Cant Stop Us All

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    foo->bar is just shorthand for (*foo).bar. If p was a vector, you would either use p[i] or p.at(i) to reference. Since p is now a pointer, *p is a vector, so (*p)[i] or (*p).at(i). This last you could write as p->at(i).

  3. #3
    Registered User (TNT)'s Avatar
    Join Date
    Aug 2001
    Location
    UK
    Posts
    339
    Thanks alot
    TNT
    You Can Stop Me, But You Cant Stop Us All

Popular pages Recent additions subscribe to a feed