Test Header HTML Code

尝试改进std::vector提高性能

    在顺序读取文件缓存大量数据时候,STL标准库中的std::vector类模板,由于其内存扩展方式,往往当容量不足时,需要先申请两倍于目前的空间,然后将现在的数据拷贝过去,这样速度很慢。
在这里我写了一个小类模板tvector,用数据块来进行扩展,类在初始化的时候,用户指定初始化大小,以及每次增长的容量大小。

 

代码
1 #ifndef T_VECTOR_H
2  #define T_VECTOR_H
3  /*
4 ** 这个类适合存储大量数据,并支持随机访问
5 */
6 #include <cassert>
7 #include <vector>
8 template<class T> class tvector
9 {
10 public:
11 typedef unsigned int size_type;
12 public:
13 tvector(size_type initSize = 1000, size_type increaseSize = 1000);
14 virtual ~tvector(void);
15
16 void push_back(const T &data); //在列表末尾添加记录
17 T& operator[] (size_type index); //支持[index]形式的随机访问
18 const T& operator[] (size_type index) const; //对const对象返回const记录
19 size_type size() const { return m_dataSize; } //记录数目
20
21 private:
22 std::vector<T*> m_dataBlocks; //记录块指针列表
23 size_type m_initSize; //初始大小
24 size_type m_increaseSize; //每次新增大小
25 size_type m_capacity; //容量
26 size_type m_dataSize; //记录条数
27 size_type m_currentBlockID; //缓存当前块ID值
28 size_type m_nextDataID; //下一条记录ID值
29 };
30
31 template<class T> tvector<T>::tvector(size_type initSize, size_type increaseSize)
32 {
33 m_initSize = initSize;
34 m_increaseSize = increaseSize;
35 T *firstBlock = new T[m_initSize];
36 assert(firstBlock != NULL);
37 memset(firstBlock, sizeof(T) * initSize, 0);
38 m_dataBlocks.push_back(firstBlock);
39 m_capacity = m_initSize;
40 m_dataSize = 0;
41 m_currentBlockID = 0;
42 m_nextDataID = 0;
43 }
44
45 template<class T> tvector<T>::~tvector()
46 {
47 for(std::vector<T*>::iterator it = m_dataBlocks.begin(); it != m_dataBlocks.end(); it++)
48 {
49 delete[] *it;
50 }
51 }
52 template<class T> void tvector<T>::push_back(const T &data)
53 {
54 if(m_capacity) //如果还有容量,直接插入
55 {
56 m_dataBlocks[m_currentBlockID][m_nextDataID++] = data;
57 m_capacity--;
58 }
59 else //申请新的空间
60 {
61 T *block = new T[m_increaseSize];
62 assert(block != NULL);
63 memset(block, sizeof(T) * m_increaseSize, 0);
64 block[0] = data;
65 m_dataBlocks.push_back(block);
66 m_currentBlockID++;
67 m_nextDataID = 1;
68 m_capacity = m_increaseSize - 1;
69 }
70 m_dataSize++;
71 }
72
73 template<class T> T& tvector<T>::operator[](size_type index)
74 {
75 if(index < m_initSize) return m_dataBlocks[0][index];
76 else
77 {
78 size_type blockID = (index - m_initSize) / m_increaseSize + 1;
79 size_type dataID = (index - m_initSize) % m_increaseSize;
80 return m_dataBlocks[blockID][dataID];
81 }
82 }
83
84 template<class T> const T& tvector<T>::operator[](size_type index) const
85 {
86 if(index < m_initSize) return m_dataBlocks[0][index];
87 else
88 {
89 size_type blockID = (index - m_initSize) / m_increaseSize + 1;
90 size_type dataID = (index - m_initSize) % m_increaseSize;
91 return m_dataBlocks[blockID][dataID];
92 }
93 }
94 #endif

 

posted on 2010-04-06 17:56  宁静的水泡  阅读(1732)  评论(4编辑  收藏  举报

导航

Test Rooter HTML Code