寻找类似于C ++ STL的向量类,但使用堆栈存储

在我写自己的书之前,我会问大家。


我正在寻找一个C ++类,该类几乎完全类似于STL向量,但将数据存储到堆栈中的数组中。某种STL分配器类也可以工作,但是我试图避免任何类型的堆,甚至是静态分配的每线程堆(尽管其中之一是我的第二选择)。堆栈效率更高。


它几乎需要替换使用矢量的当前代码。


对于我要写的自己,我在想这样的事情:


char buffer[4096];

stack_vector<match_item> matches(buffer, sizeof(buffer));

或者该类可以在内部分配缓冲区空间。然后看起来像:


stack_vector<match_item, 256> matches;

我以为如果空间不足,它会抛出std :: bad_alloc,尽管那永远不会发生。


更新资料


使用Chromium的stack_container.h效果很好!


我自己没有考虑过这样做的原因是,我一直忽略了STL集合构造函数的allocator对象参数。我已经多次使用template参数来进行静态池,但是我从未见过代码或编写任何实际使用object参数的代码。我学到新东西。很酷!


代码有点混乱,由于某种原因,GCC迫使我将分配器声明为实际项,而不是将其构造为vector的分配器参数。它来自这样的事情:


typedef std::pair< const char *, const char * > comp_list_item;

typedef std::vector< comp_list_item > comp_list_type;


comp_list_type match_list;

match_list.reserve(32);

对此:


static const size_t comp_list_alloc_size = 128;

typedef std::pair< const char *, const char * > comp_list_item;

typedef StackAllocator< comp_list_item, comp_list_alloc_size > comp_list_alloc_type;

typedef std::vector< comp_list_item, comp_list_alloc_type > comp_list_type;


comp_list_alloc_type::Source match_list_buffer;

comp_list_alloc_type match_list_alloc( &match_list_buffer );

comp_list_type match_list( match_list_alloc );

match_list.reserve( comp_list_alloc_size );

每当我宣布一个新的时,我都必须重复一遍。但这就像我想要的那样工作。


我注意到stack_container.h定义了StackVector,我尝试使用它。但是它不继承自vector或定义相同的方法,因此它不是直接替代。我不想使用向量重写所有代码,所以我放弃了。


炎炎设计
浏览 483回答 3
3回答

噜噜哒

如果速度很重要,我会看到运行时间4 ns int [10],在堆栈上固定大小40纳秒 <vector>1300纳秒 <stlsoft/containers/pod_vector.hpp>对于以下一项愚蠢的测试-只需2次推送,v [0] v [1],2个pop,在一个平台上,仅限mac ppc,gcc-4.2 -O3。(我不知道苹果是否优化了他们的stl。)不要接受您没有伪造自己的时间。当然,每种使用方式都不同。但是> 2的因素令我感到惊讶。(如果内存,内存访问是运行时的主要因素,那么各种实现中所有额外的内存是什么?)#include <stlsoft/containers/pod_vector.hpp>#include <stdio.h>using namespace std;int main( int argc, char* argv[] ){&nbsp; &nbsp; &nbsp; &nbsp; // times for 2 push, v[0] v[1], 2 pop, mac g4 ppc gcc-4.2 -O3 --&nbsp; &nbsp; // Vecint10 v;&nbsp; // stack int[10]: 4 ns&nbsp; &nbsp; vector<int> v;&nbsp; // 40 ns&nbsp; &nbsp; // stlsoft::pod_vector<int> v;&nbsp; // 1300 ns&nbsp; &nbsp; // stlsoft::pod_vector<int, std::allocator<int>, 64> v;&nbsp; &nbsp; int n = (argv[1] ? atoi( argv[1] ) : 10) * 1000000;&nbsp; &nbsp; int sum = 0;&nbsp; &nbsp; while( --n >= 0 ){&nbsp; &nbsp; &nbsp; &nbsp; v.push_back( n );&nbsp; &nbsp; &nbsp; &nbsp; v.push_back( n );&nbsp; &nbsp; &nbsp; &nbsp; sum += v[0] + v[1];&nbsp; &nbsp; &nbsp; &nbsp; v.pop_back();&nbsp; &nbsp; &nbsp; &nbsp; v.pop_back();&nbsp; &nbsp; }&nbsp; &nbsp; printf( "sum: %d\n", sum );}
打开App,查看更多内容
随时随地看视频慕课网APP