std::vector and c-style arrays

前端 未结 1 569
滥情空心
滥情空心 2021-02-15 09:50

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

1条回答
  •  孤独总比滥情好
    2021-02-15 10:22

    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.

    0 讨论(0)
提交回复
热议问题