【发布时间】:2014-11-01 21:45:54
【问题描述】:
您好,我在编写此函数时遇到问题:
int& ArrayVector::operator[](int index)
必须做到以下几点
返回对数组第索引元素的引用
如果索引大于或等于数组的大小, 1.扩大数组覆盖到(index+1) 元素 2. 将元素从旧数组复制到扩展数组 3. 从第 n 到第 (index-1) 的元素填充 0 4. 返回第 index 个元素 还要跟踪数组的大小 到目前为止,这是我的课。我只需要有关此功能的帮助。谢谢!!
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
}
【问题讨论】:
-
好的,那么您尝试了哪些方法,如果遇到困难,您在哪一步遇到了问题?
-
您的
print()函数可能看起来像for(int i = 0; i < n; i++) cout << data[i] << " ";...无需将最后一个元素与for loop分开,如果n等于0那么 for 循环中的语句将永远不会发生所以不需要检查 0 数组大小 -
哦,既然我们已经有了
std::vector,为什么还要实现自己的课程? -
@Quest 从非常具体的说明中可以明显看出这很可能是某种类型的分配
标签: c++ arrays c++11 vector operator-overloading