ArrayVector类的运算符[]重载
Overloading operator[] for ArrayVector class
嗨,我在写这个函数时遇到问题:
int& ArrayVector::operator[](int index)
它必须执行以下
返回对数组的索引第th个元素的引用
如果索引大于或等于数组的大小,1.将数组扩展到(索引+1)元素2.将元素从旧数组复制到扩展数组3.为从第n个到第(索引-1)个的元素填充04.返回索引第th个元素还要跟踪阵列的大小到目前为止,这是我的课。我只需要这个功能的帮助。谢谢
class ArrayVector {
private:
int* data;
int n;
public:
ArrayVector() : data(NULL), n(0) { }
int size() const {
return n;
}
// print content of the array separated by “ “
void print() {
if (n == 0)
return;
// print from first element to second last element
for (int i = 0; i < n-1; ++i)
cout << data[i] << " ";
// print last element
cout << data[n-1] << endl;
}
// Return reference to index-th element of the array
// If index is greater or equal to size of the array,
// 1. expand the array to cover up to (index+1)
// elements
// 2. copy elements from old array to expanded array
// 3. fill 0 for elements from n-th to (index-1)-th
// 4. return the index-th element
// Also keep track the size of the array
int& operator[](const int index);
};
int& ArrayVector::operator[](int index) {
// TODO
}
如果索引在范围内,只需返回元素。其他:将大小为(n+(n-index+1))的新数组分配到临时指针中。使用for循环复制前"n"个值。将0放入新数组的其余部分。将"n"设置为新大小,删除旧的已分配数组。将"data"设置为指向新数据。返回元素。
您的operator[]
可以如下所示:
int& ArrayVector::operator[](int index)
{
if(index > 0 && index < n)
return data[index]; // if index is in range, just return an element
else{ // if not,
int *nData = new int[index+1]; // create a new, temporarily array with size index+1
for(int i = 0; i < n; i++)
nData[i] = data[i]; // copy data to our new aray
delete[] data; // delete our old array
for(int i = n; i < index+1; i++)
nData[i] = 0; // fill newly created elements with 0
data = nData; // set data to point to our new created array
n = index+1; // set new data size
return data[index]; // return element with that index
}
}
您可以拥有这个
int& operator[](const int index){
if(index>0 && index<n){
return data[index];
}
else if(index>n){
int *newData = new int[index+1];
for(int i=0;i<n;i++){
newData[i]=data[i];
}
for(int i=n;i<index+1;i++){
newData[i]=0;
}
return newData[index];
}else{
return;
}
};
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用