Using std::vector as view on to raw memory

后端 未结 10 1687
感动是毒
感动是毒 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:55

    Since the algorithm-library works with iterators you can keep the array.

    For pointers and known array length

    Here you can use raw pointers as iterators. They support all the opertations an iterator supports (increment, comparison for equality, value of, etc...):

    #include 
    #include 
    
    int *get_data_from_library(int &size) {
        static int data[] = {5,3,2,1,4}; 
    
        size = 5;
    
        return data;
    }
    
    
    int main()
    {
        int size;
        int *data = get_data_from_library(size);
    
        std::sort(data, data + size);
    
        for (int i = 0; i < size; i++)
        {
            std::cout << data[i] << "\n";
        }
    }
    

    data points to the dirst array member like an iterator returned by begin() and data + size points to the element after the last element of the array like an iterator returned by end().

    For arrays

    Here you can use std::begin() and std::end()

    #include 
    #include 
    
    int main()
    {
        int data[] = {5,3,2,1,4};         // raw data from library
    
        std::sort(std::begin(data), std::end(data));    // sort raw data in place
    
        for (int i = 0; i < 5; i++)
        {
            std::cout << data[i] << "\n";   // display sorted raw data 
        }
    }
    

    But keep in mind that this only works, if data does not decay to a pointer, because then length information goes missing.

提交回复
热议问题