gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:21:48 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com