当c 中的矢量容器过载[]运算符时,我对未定义的索引返回什么
What do I return for undefined index when overloading [] operator for vector container in C++?
我刚刚开始在C 中实现一个基本的向量容器。它远非完成,但看起来像这样:
using namespace std;
typedef unsigned long long int bigInt;
namespace stl2{
template<class T>
class vector{
private:
bigInt l;
bigInt cap;
T* arr;
public:
vector(){
cap = 0;
l = 0;
}
~vector(){
if (cap > 0) delete[] arr;
}
vector(bigInt size){
cap = size;
l = size;
arr = new T[size];
}
vector(bigInt size, const T& def) : vector(size){
for (bigInt i = 0; i < size; i++){
arr[i] = def;
}
}
bigInt size(){
return l;
}
bigInt length(){
return l;
}
bigInt capacity(){
return cap;
}
void resize(bigInt size){
if (size < cap) return;
l = size;
cap = size;
}
void push_back(const T& data){
// Check if vector is full
if (l == cap) {
//Copy all elements of this vector to another
if (cap == 0)
cap = 1;
else
cap *= 2;
T* temp = new T[cap];
for (int i = 0; i < l; i++){
temp[i] = arr[i];
}
delete[] arr;
arr = temp;
}
arr[l] = data;
l++;
}
//Operators
T& operator[](bigInt index){
if (index < cap)
return arr[index];
}
};
}
所以我对[]运算符有问题。我知道如果索引&lt;容量,我可以返回ARR [索引]。但是,如果索引大于或等于>容量,我该返回什么?由于我正在返回对元素的引用,因此我无法返回一个值。
std::vector
在使用无效索引的at()
时会引发异常,您可以执行相同的操作。
std::vector
的operator[]
不执行界限检查,使用无效的索引是未定义的行为。
相关文章:
- 一元"运算符"未在C++中定义
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- 未定义的引用和运算符 << vs me
- C++:对函子重载调用运算符的未定义引用
- 对模板运算符的未定义引用,其定义位于同一头文件中
- 在 tensorflow-GPU 中使用用户运算符时未定义的符号>=1.15
- 为什么T是未定义的?我正在尝试实现一个用于双链表的节点类,它不喜欢我使用友元运算符后的T
- 调用提取重加载器会产生对"运算符"的未定义引用错误>>
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 编译Qt项目给出了对运算符delete(void*,unsigned int)的未定义引用
- 在 C 和 C++ 中,使用逗号运算符的表达式是否未定义"a = b, ++a;"?
- 未定义对运算符的引用!= 使用 std::unordered_set 时
- C2676 - 二进制'++'未定义此运算符
- 尝试编写进程内存并获取用户定义的文字运算符未找到
- 未定义 Lambda 复制分配运算符
- 为什么要重载以前未定义的运算符
- std::可选运算符*() 和运算符>() - 未定义的行为
- std::映射运算符[]--未定义的行为
- 获取函数运算符<未定义的引用
- 错误:"运算符 []"未定义