Vector/Pointer Help

This is a discussion on Vector/Pointer Help within the C++ Programming forums, part of the General Programming Boards category; Hi, If i have a pointer to a vector what is the correct syntax to access an element of the ...

  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,185
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21