将动态数组包装到 STL/Boost 容器中?

2022-01-24 00:00:00 arrays containers vector c++ boost

我需要将一个动态分配的数组(例如从 a = new double[100] 中)包装到 std::vector(最好)而不复制数组.这个限制是由于我要包装的数组是从文件中映射的,所以只需执行 vector(a, a+size) 就会使内存使用量加倍.

I need to wrap a dynamically allocated array(from a = new double[100] for example) into std::vector(preferably) without copying the array. This restriction is imposed by that the array I want to wrap is mmaped from a file, so just doing vector(a, a+size) will double the memory usage.

有什么技巧可以做到吗?

Is any tricks to do that?

推荐答案

最好的解决方案之一是 STLSoft 的 array_proxy<> 模板.不幸的是,doxygen 从源代码生成的文档页面对理解模板没有很大帮助.源代码实际上可能更好一点:

One of the best solutions for this is something like STLSoft's array_proxy<> template. Unfortunately, the doc page generated from the source code by doxygen isn't a whole lot of help understanding the template. The source code might actually be a bit better:

  • http://www.stlsoft.org/doc-1.9/array__proxy_8hpp-source.html

array_proxy<> 模板在 Matthew Wilson 的文章中有很好的描述书,不完美的 C++.我使用的版本是 STLSoft 网站上的精简版本,所以我不必拉入整个库.我的版本不那么便携,但这使它比 STLSoft 上的要简单得多(它跳过了很多可移植性箍).

The array_proxy<> template is described nicely in Matthew Wilson's book, Imperfect C++. The version I've used is a cut-down version of what's on the STLSoft site so I didn't have to pull in the whole library. My version's not as portable, but that makes it much simpler than what's on STLSoft (which jumps through a whole lot of portability hoops).

如果你像这样设置一个变量:

If you set up a variable like so:

int myArray[100];

array_proxy<int> myArrayProx( myArray);

变量myArrayProx有很多STL接口――begin()end()size()、迭代器等

The variable myArrayProx has many of the STL interfaces - begin(), end(), size(), iterators, etc.

所以在许多方面,array_proxy<> 对象的行为就像一个向量(尽管 push_back() 不存在,因为 array_proxy<> 不能增长 - 它不管理数组的内存,它只是将它包装在更接近向量的东西中).

So in many ways, the array_proxy<> object behaves just like a vector (though push_back() isn't there since the array_proxy<> can't grow - it doesn't manage the array's memory, it just wraps it in something a little closer to a vector).

array_proxy<> 的一个真正好处是,如果将它们用作函数参数类型,则函数可以确定传入数组的大小,而原生数组则不然.并且包装数组的大小不是模板类型的一部分,因此使用起来非常灵活.

One really nice thing with array_proxy<> is that if you use them as function parameter types, the function can determine the size of the array passed in, which isn't true of native arrays. And the size of the wrapped array isn't part of the template's type, so it's quite flexible to use.

相关文章