Using std::vector as view on to raw memory

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

    As others have pointed out, std::vector must own the underlying memory (short of messing with a custom allocator) so can't be used.

    Others have also recommended c++20's span, however obviously that requires c++20.

    I would recommend the span-lite span. To quote it's subtitle:

    span lite - A C++20-like span for C++98, C++11 and later in a single-file header-only library

    It provides a non-owning and mutable view (as in you can mutate elements and their order but not insert them) and as the quote says has no dependencies and works on most compilers.

    Your example:

    #include 
    #include 
    #include 
    
    #include 
    
    static int data[] = {5, 1, 2, 4, 3};
    
    // For example
    int* get_data_from_library()
    {
      return data;
    }
    
    int main ()
    {
      const std::size_t size = 5;
    
      nonstd::span v{get_data_from_library(), size};
    
      std::sort(v.begin(), v.end());
    
      for (auto i = 0UL; i < v.size(); ++i)
      {
        std::cout << v[i] << "\n";
      }
    }
    

    Prints

    1
    2
    3
    4
    5
    

    This also has the added upside if one day you do switch to c++20, you should just be able to replace this nonstd::span with std::span.

提交回复
热议问题