Converting between C++ std::vector and C array without copying

前端 未结 5 1294
清酒与你
清酒与你 2020-12-02 08:34

I would like to be able to convert between std::vector and its underlying C array int* without explicitly copying the data.

Does std::vector provide access to the u

5条回答
  •  既然无缘
    2020-12-02 09:30

    If you have very controlled conditions, you can just do:

    std::vector v(4,100);
    int* pv = &v[0];
    

    Be warned that this will only work as long as the vector doesn't have to grow, and the vector will still manage the lifetime of the underlying array (that is to say, don't delete pv). This is not an uncommon thing to do when calling underlying C APIs, but it's usually done with an unnamed temporary rather than by creating an explicit int* variable.

提交回复
热议问题