c++ - 模板中的数组和指针

标签 c++ arrays pointers

我正在尝试编写一个具有一些功能的模板/类,但我遇到了一个看起来相当新手的问题。我有一个简单的插入函数和一个显示值函数,但是每当我尝试显示值时,我总是收到看起来像内存地址的东西(但我不知道),但我想接收存储的值(在这个具体示例,int 2)。我不确定如何将其取消引用为一个值,或者我是否完全搞砸了。我知道 vector 是更​​好的选择,但是我需要在此实现中使用数组 - 老实说,我想更透彻地了解代码和正在发生的事情。对于如何完成此任务的任何帮助,我们将不胜感激。

示例输出(每次都以相同的方式运行程序): 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来自未初始化的指针。设置valuesnew Comparable[0]在构造函数中。

第二,memcpy正确的字节数:(currentSize-1)*sizeof(Comparable) .

三、不要memcpy根本。假设 Comparable类型都可以逐字节复制,这是 C++ 中的一个严重限制。相反:

编辑:更改uninitialized_copycopy :

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 .

关于c++ - 模板中的数组和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12354216/

相关文章:

c++ - OpenCV 2.4.3 到 2.4.9 版本变更

c++ - 可变参数宏 : cannot pass objects of non-trivially-copyable type through '...'

c - file.exe 已停止工作

javascript - 使用 LODASH 比较 2 个数组来查找缺失的信息

swift - 将 PFObject 指针转换为解析中的子类(swift)

c++ - 由单个进程的多个实体链接的库中的全局变量

c++ - 我如何 curry 可变参数模板模板参数?

php - 数组合并/替换

c - 数组不会使用指针在 C 中反向打印

c++ - 在同一函数中引用范围外的局部变量是否可以?