std::vector and c-style arrays

前端 未结 3 2020
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 09:49

I am experimenting with OpenCL to increase the speed of our software. We work with maps a lot and, to simplify, represent a map as a std::vector< std::vector >. The OpenCL AP

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-15 10:21

    Are there implementation guarantees in the stl that vector is, internally, consecutive in memory?

    As of C++03, yes, a vector is guaranteed to use contiguous storage. (In C++98, there was an accidental loophole so an implementation could hypothetically use non-contiguous storage, but it was fixed in the 2003 revision of the standard - and no implementation actually used non-contiguous storage because it'd be a terrible idea)

    Can I safely cast a std::vector to int* and expect that to work?

    The usual way is &v[0]. (&*v.begin() would probably work too, but I seem to recall there's some fluffy wording in the standard that makes this not 100% reliable)

    No. Why would you expect that to work? A vector is a class. It is not a pointer. It just contains a pointer.

    In the case of a vector of vectors, can I still assume this holds true? I would expect the vector to hold other state data, or alignment issues, or maybe something else...

    The vector behaves the same whatever you store in it. If you make a vector of vectors, you end up with an object which contains a pointer to a heap-allocated array, where each element is an object which contains a pointer to a heap-allocated array.

    As for how you should approach this, it depends on a lot of factors. How big is your total dataset? You might want to have the entire table allocated contiguously. With a vector of vectors, each row is a separate allocation.

提交回复
热议问题