Algorithm | Vector
2024-10-20 03:59:10
因为平常用的话只是vector的一些非常简单的功能,基本上把它当数组来用,现在也只是把这一部分写了一些。
template<class T>
class XVector {
public:
XVector(int cacheSize):cacheSize(cacheSize), count() {
data = new T[cacheSize];
}
XVector():cacheSize(), count() {
data = new T[cacheSize];
} ~XVector() {
delete[] data;
} void push_back(T val) {
if (count >= cacheSize) {
cacheSize <<= ;
T* copy = new T[cacheSize];
memcpy(copy, data, sizeof(T) * count);
delete[] data;
data = copy;
}
data[count++] = val;
} void pop_back() {
count--;
} int size() const {
return count;
} T& operator[](int index) {
//return const_cast<T&>(operator[](index));
return const_cast<T&>((static_cast<const XVector<T>&>(*this))[index]);
} const T& operator[](int index) const {
return data[index];
} private:
int count;
int cacheSize;
T *data;
};
但是注意在用非const的operator[]函数调用const版本的operator[]函数时,应该先用static_cast强制将this转成const,这样才能调用到const版本的函数。这一个过程是安全的。然后再将返回的const T&去掉const,这个过程也是非const函数需要承担的风险。
最新文章
- Linux环境下常用软件(个人笔记编辑更改中)
- sqlserver存储过程批量插入数据
- 【每日学习】Apache重写未开启,导致The requested URL /xxxx.html was not found on this server
- 如何生成excel文件作为图像识别结果
- php中fopen函数用法详解(打开文件)
- 【HDOJ】1542 Atlantis
- oracle_有关表分区_查询
- 翻译 | 一行 JavaScript 代码的逆向工程
- Python面向对象——基本继承
- BBS论坛(十八)
- c#进程、定时器初步学习
- pom中Maven插件 配置 maven-dependency-plugin maven-surefire-plugin
- iOS------App之间传递数据的几种方式
- React-Redux使用方法
- Aspose 插件
- python 列表的浅拷贝和深拷贝
- 微信第三方登录测试时报Scope参数错误或没有Scope权限解决方法
- 学习python网站
- stutas2配置action
- 64位系统InlineHook