给定一个原始数组元素,如何创建一个 std::vector
来获取原始数组的所有权而无需重新分配和复制?
例如有原始数组:
int* elems = new int[33]
如何创建大小为 33
并指向 elems
的 std::vector
?
我确信理论上这是可能的,因为通常 std::vector
被实现为包含三个指针的结构,一个指向分配内存的开头,一个指向分配内存的结尾有效元素,一个到分配内存的末尾。但是有没有一种标准方法可以用原始数组初始化 std::vector
结构?
最佳答案
您需要的是“ View ”而不是容器。容器拥有它们的元素,它们的主要目的是封装它们管理的原始内存。如果您需要自己管理内存,则不需要容器。看看 string_view
如果您有一个 string
,这将是您的解决方案。也许boost ranges是你可以申请的东西。来自文档(强调我的):
The motivation for the Range concept is that there are many useful Container-like types that do not meet the full requirements of Container, and many algorithms that can be written with this reduced set of requirements. In particular, a Range does not necessarily
- own the elements that can be accessed through it,
- have copy semantics,
PS:实际上 std::array_view
被考虑用于 C++17,但不幸的是它没有成为标准。
关于c++ - 从原始数据就地创建 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236167/