Using std::vector as view on to raw memory

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

    You could use a std::reference_wrapper available since C++11:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        int src_table[] = {5, 4, 3, 2, 1, 0};
    
        std::vector< std::reference_wrapper< int > > dest_vector;
    
        std::copy(std::begin(src_table), std::end(src_table), std::back_inserter(dest_vector));
        // if you don't have the array defined just a pointer and size then:
        // std::copy(src_table_ptr, src_table_ptr + size, std::back_inserter(dest_vector));
    
        std::sort(std::begin(dest_vector), std::end(dest_vector));
    
        std::for_each(std::begin(src_table), std::end(src_table), [](int x) { std::cout << x << '\n'; });
        std::for_each(std::begin(dest_vector), std::end(dest_vector), [](int x) { std::cout << x << '\n'; });
    }
    

提交回复
热议问题