以下是基本问题。我依赖于一个API,其中有一个使用以下语法的方法:
void foo_api (std::vector<type>& ref_to_my_populated_vector);
所涉及的代码区域相当性能密集,我想避免使用堆来分配内存。因此,我创建了一个自定义分配器,在堆栈上分配向量所需的内存。因此,现在可以定义一个向量:
// Create the stack allocator, with room for 100 elements
my_stack_allocator<type, 100> my_allocator;
// Create the vector, specifying our stack allocator to use
std::vector<type, my_stack_allocator> my_vec(my_allocator);
这一切都很好。使用堆栈分配的向量进行性能测试,与标准向量相比,性能大约快了4倍。问题是,我无法调用foo_api!所以...
foo_api(my_vec); // Results in an error due to incompatible types.
// Can't convert std::vector<type> to std::vector<type, allocator>
这个问题有解决方案吗?
std::vector<type, my_stack_allocator>
应该改为std::vector<type, my_stack_allocator<type, 100>>
,是吗?在这里使用typedef
会有帮助。 - GManNickGtemplate<typename Iter> void foo_api(Iter begin, Iter end);
,那就很好和通用,可以与任何容器一起使用。 - John Diblingtemplate <typename Sequence> void foo_api(Sequence &ref);
,这样就不需要太多修改 foo_api 的代码。这取决于它使用 vector 的哪些成员函数。如果 foo_api 可能添加/删除任意元素,则使用迭代器编写 API 的唯一方法是进行复制和修改。 - Steve Jessop