我正在尝试编写具有一些功能的模板/类,但是遇到了一个相当新手的问题。我有一个简单的插入函数和一个显示值函数,但是,每当我尝试显示该值时,我总是会收到一个看起来像内存地址的东西(但我不知道),但是我想接收存储的值(在此)具体示例,int 2)。我不确定如何将其取消引用为值,或者我是否完全搞砸了。我知道向量是更好的选择,但是我需要在此实现中使用数组-老实说,我想对代码以及正在发生的事情有更全面的了解。对于如何完成此任务的任何帮助将不胜感激。
输出示例(每次以相同的方式运行程序):
003358C0
001A58C0
007158C0
码:
#include <iostream>
using namespace std;
template <typename Comparable>
class Collection
{
public: Collection() {
currentSize = 0;
count = 0;
}
Comparable * values;
int currentSize; // internal counter for the number of elements stored
void insert(Comparable value) {
currentSize++;
// temparray below is used as a way to increase the size of the
// values array each time the insert function is called
Comparable * temparray = new Comparable[currentSize];
memcpy(temparray,values,sizeof values);
// Not sure if the commented section below is necessary,
// but either way it doesn't run the way I intended
temparray[currentSize/* * (sizeof Comparable) */] = value;
values = temparray;
}
void displayValues() {
for (int i = 0; i < currentSize; i++) {
cout << values[i] << endl;
}
}
};
int main()
{
Collection<int> test;
int inserter = 2;
test.insert(inserter);
test.displayValues();
cin.get();
return 0;
}
最佳答案
好吧,如果您坚持要写,可以编写和调试自己的受限版本的std::vector
。
首先,不要在未初始化的指针中输入memcpy
。在构造函数中将values
设置为new Comparable[0]
。
其次,memcpy
正确的字节数:(currentSize-1)*sizeof(Comparable)
。
第三,完全不要memcpy
。假定Comparable
类型都可以逐字节复制,这在C ++中是一个严格的限制。代替:
编辑:将uninitialized_copy
更改为copy
:
std::copy(values, values + currentSize - 1, temparray);
第四,删除不再使用的旧数组:
delete [] values;
第五,除非代码很少插入,否则将数组扩展一倍以上。
std::vector
通常将其大小增加1.5倍。第六,在大小改变之前,不要增加
currentSize
。这会将所有这些currentSize-1
更改为currentSize
,这很麻烦。 <g>
第七,大小为
N
的数组具有从0
到N-1
的索引,因此新数组的顶部元素位于currentSize - 1
,而不是currentSize
。第八,我提到过,您确实应该使用
std::vector
。