c++ - How to construct a std::vector or a boost::array from a C array without copying? -


given pointer array of char, possible construct std::vector or boost::array it, , avoiding memory copying?

thanks in advance!

because vectors own own allocators , storage alike, there no way (for non primitive elements construction move_iterators bit).

so assuming goal true std::vector<char>& existing storage, you'll never succeed, not custom allocators¹.


if want string, can use boost::string_ref (in utility/string_ref.hpp).

otherwise, use 1-dimensional multi_array_ref (from boost multi array)

1. using string_ref

this easiest:

live on coliru

#include <boost/utility/string_ref.hpp> #include <iostream>  using boost::string_ref;  int main() {     char some_arr[] = "hello world";      string_ref no_copy(some_arr);      std::cout << no_copy; } 

2. multi_array_ref

this more versatile, , works "better" if not geared towards string interface.

live on coliru

#include <boost/multi_array/multi_array_ref.hpp> #include <iostream>  using ref = boost::multi_array_ref<char, 1>; using boost::extents;  int main() {     char some_arr[] = "hello world";      ref no_copy(some_arr, extents[sizeof(some_arr)]);      std::cout.write(no_copy.data(), no_copy.num_elements()); } 

both examples print

hello world 

¹ specializing std::allocator<char> evil consider , outright prohibited standard


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -