Convert iterator to pointer?

前端 未结 12 2276
野性不改
野性不改 2020-12-14 14:20

I have a std::vector with n elements. Now I need to pass a pointer to a vector that has the last n-1 elements to a function.

F

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 14:48

    For example, my vector foo contains (5,2,6,87,251). A function takes vector* and I want to pass it a pointer to (2,6,87,251).

    A pointer to a vector is not at all the same thing as a pointer to the elements of the vector.

    In order to do this you will need to create a new vector with just the elements you want in it to pass a pointer to. Something like:

     vector tempVector( foo.begin()+1, foo.end());
    
     // now you can pass &tempVector to your function
    

    However, if your function takes a pointer to an array of int, then you can pass &foo[1].

提交回复
热议问题