• 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函数需要承担的风险。

  • 相关阅读:
    Windows Azure入门教学系列 (九):Windows Azure 诊断功能
    批量删除同类文件的函数
    Edit 的使用
    @ 与 ^ 运算符
    窗体相关操作
    uses 子句的写法
    goto 语句
    字符串常识
    not 与整数
    Memo 的当前行、当前列与当前字符
  • 原文地址:https://www.cnblogs.com/linyx/p/3774665.html
Copyright © 2020-2023  润新知