Algorithm | Vector

 因为平常用的话只是vector的一些非常简单的功能,基本上把它当数组来用,现在也只是把这一部分写了一些。

 1 template<class T>
 2 class XVector {
 3 public:
 4     XVector(int cacheSize):cacheSize(cacheSize), count(0) {
 5         data = new T[cacheSize];
 6     }
 7     XVector():cacheSize(100), count(0) {
 8         data = new T[cacheSize];
 9     }
10 
11     ~XVector() { 
12         delete[] data;
13     }
14 
15     void push_back(T val) {
16         if (count >= cacheSize) {
17             cacheSize <<= 1;
18             T* copy = new T[cacheSize];
19             memcpy(copy, data, sizeof(T) * count);
20             delete[] data;
21             data = copy;
22         }
23         data[count++] = val;
24     }
25 
26     void pop_back() {
27         count--;
28     }
29 
30     int size() const {
31         return count;
32     }
33 
34     T& operator[](int index) {
35         //return const_cast<T&>(operator[](index));
36         return const_cast<T&>((static_cast<const XVector<T>&>(*this))[index]);
37     }
38     
39     const T& operator[](int index) const {
40         return data[index];
41     }
42 
43 private:
44     int count;
45     int cacheSize;
46     T *data;
47 };

但是注意在用非const的operator[]函数调用const版本的operator[]函数时,应该先用static_cast强制将this转成const,这样才能调用到const版本的函数。这一个过程是安全的。然后再将返回的const T&去掉const,这个过程也是非const函数需要承担的风险。

原文地址:https://www.cnblogs.com/linyx/p/3774665.html