Using std::vector as view on to raw memory

后端 未结 10 1613
感动是毒
感动是毒 2021-01-31 13:34

I\'m using a external library which at some point gives me a raw pointer to an array of integers and a size.

Now I\'d like to use std::vector to access and

10条回答
  •  滥情空心
    2021-01-31 13:45

    You can get iterators on raw arrays and use them in algorithms:

        int data[] = {5,3,2,1,4};
        std::sort(std::begin(data), std::end(data));
        for (auto i : data) {
            std::cout << i << std::endl;
        }
    

    If you are working with raw pointers (ptr + size), then you can use the following technique:

        size_t size = 0;
        int * data = get_data_from_library(size);
        auto b = data;
        auto e = b + size;
        std::sort(b, e);
        for (auto it = b; it != e; ++it) {
            cout << *it << endl;
        }
    

    UPD: However, the above example is of bad design. The library returns us a raw pointer and we don't know where the underlying buffer is allocated and who is supposed to free it.

    Usually, the caller provides a buffered for the function to fill the data. In that case, we can preallocate the vector and use its underlying buffer:

        std::vector v;
        v.resize(256); // allocate a buffer for 256 integers
        size_t size = get_data_from_library(v.data(), v.size());
        // shrink down to actual data. Note that no memory realocations or copy is done here.
        v.resize(size);
        std::sort(v.begin(), v.end());
        for (auto i : v) {
            cout << i << endl;
        }
    

    When using C++11 or above we can even make get_data_from_library() to return a vector. Thanks to move operations, there will be no memory copy.

提交回复
热议问题