模板中的数组和指针

时间:2012-09-10 14:52:22

标签: c++ arrays pointers

我正在尝试编写一个具有一些功能的模板/类,但我遇到的似乎是一个相当新手的问题。我有一个简单的插入函数和一个显示值函数,但每当我尝试显示值时,我总是收到看起来像内存地址的东西(但我不知道),但我想收到存储的值(在此特别的例子,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;
}

3 个答案:

答案 0 :(得分:2)

这一行错了:

memcpy(temparray,values,sizeof values);

第一次运行此行时,values指针未初始化,因此会导致未定义的行为。此外,使用sizeof values是错误的,因为它总是会给出指针的大小。

另一个问题:

temparray[currentSize] = value; 

这也会导致未定义的行为,因为您只在currentSize中分配了temparray项,因此您只能访问0currentSize-1的索引。

答案 1 :(得分:2)

好吧,如果你坚持,你可以编写和调试你自己的限量版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的数组的索引从0N-1,因此新数组的顶部元素位于currentSize - 1,而不是currentSize }。

第八,我提到过,真的应该使用std::vector

答案 2 :(得分:0)

您的阵列访问也有错误。

temparray[currentSize/* * (sizeof Comparable) */] = value;

请记住,数组从索引零开始。因此,对于长度为1的数组,您可以设置temparray [0] = value。由于您在insert函数的顶部增加currentSize,因此您需要执行此操作:

temparray[currentSize-1] = value;