只是为了澄清这是我的编程任务的一部分,我知道人们在询问硬件时是多么讨厌,但我很困惑,我目前对该主题的理解需要澄清。
我需要创建一个名为 UniqueVector 的类,我必须使用动态数组(不允许使用 vector )来创建它。数组中的所有数据都必须是唯一的(没有重复)。现在一开始它们都应该以 3 码开头,但里面什么也没有。我相信我是对的,但我可能是错的。
#include <iostream>
using namespace std;
template<typename T>
class UniqueVector {
public:
UniqueVector();
unsigned int capacity();//Returns the size of the space currently allocated for the vector.
unsigned int size(); //- Returns the current number of elements in the vector.
private:
T* uniVector;
};
template<typename T>
UniqueVector<T> :: UniqueVector(){
uniVector = new T[3]; // default constructor
delete []uniVector;
}
template<typename T>
unsigned int UniqueVector<T> :: capacity()
{
int uni_size= sizeof(uniVector)/sizeof(uniVector[0]);
cout << uni_size << endl; //Gives 1
return (3); //forcing return size 3 even tho it is wrong
}
template<typename T>
unsigned int UniqueVector<T> :: size()
{
int unique_size=0;
for(int i=0; i<3; i++){
cout <<i<<" "<< uniVector[i] << endl; //[0] and [1] gives values? But [2] doesnt as it should
if(uniVector[i]!=NULL){ //Only [2] is empty for some reason
unique_size++; // if arrays arent empty, adds to total
}
};
return (unique_size);
}
int main()
{
UniqueVector<int> testVector;
cout<< "The cap is " << testVector.capacity() << endl;
cout<< "The size is " <<testVector.size() << endl;
return 0;
}
起初,如果它只是一个私有(private)的 T uniVector [3] 并且没有默认构造函数,我的 capacity 函数就可以工作,但现在它应该是 3 时只返回 1。
Size() 从一开始就没用过,因为当我只输入尺寸时,我知道如何创建值。
最佳答案
uniVector = new T[3]; // default constructor
delete []uniVector;
首先,此构造函数分配一个包含三个 T
的数组。
然后,立即删除这个数组。
这没有意义。
此外,模板的其余部分假定 uniVector
是一个有效的指针。如果不是,因为它指向的数组已被删除。这是未定义的行为。
template<typename T>
unsigned int UniqueVector<T> :: capacity()
{
int uni_size= sizeof(uniVector)/sizeof(uniVector[0]);
cout << uni_size << endl; //Gives 1
return (3); //forcing return size 3 even tho it is wrong
}
uniVector
是指向 T
的指针。因此,sizeof(uniVector)
为您提供指针的大小(以字节为单位)。然后,除以 uniVector
指向的大小,会产生一个完全没有意义的结果。
很明显,您需要跟踪分配的数组的大小。 sizeof
不会给你那个。 sizeof
是一个常量表达式。 uniVector
指针的大小完全相同,无论它指向一个 3 个值的数组,还是一个百万个值的数组。
在构造函数中,您需要做的是分配大小为 3 的初始数组,然后将 3 存储在跟踪数组容量的类成员中,然后是您的 capacity()
类方法简单地返回这个类成员的值。
同样,您还需要跟踪数组的实际大小,构造函数将其初始化为 0。
这应该足以让您入门。
关于c++ - 在类中创建一个空的动态数组,访问时赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693422/