如何在不复制的情况下从C数组构造std :: vector或boost ::数组?

Luc*_*dus 3 c++ arrays boost stdvector

给定一个char数组的指针,是否可以从中构造一个std :: vector或boost :: array,并避免内存复制?

提前致谢!

seh*_*ehe 6

因为向量拥有自己的分配器和存储器,所以没有办法(对于move_iterators的非原始元素构造可能有所帮助).

因此,假设目标是获得std::vector<char>&现有存储的真实,那么即使使用自定义分配器,也不会成功.


如果你想要一个字符串,你可以使用boost::string_ref(in utility/string_ref.hpp).

否则,您可以使用1维multi_array_ref(来自Boost Multi Array)

1.使用string_ref

这绝对是最简单的:

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;
}
Run Code Online (Sandbox Code Playgroud)

2. multi_array_ref

这是更多功能的,如果你不适合字符串界面,它会"更好".

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());
}
Run Code Online (Sandbox Code Playgroud)

两个例子打印

hello world
Run Code Online (Sandbox Code Playgroud)

¹专业化std::allocator<char>是太邪恶无法考虑,可能完全被标准所禁止