在类中创建一个空的动态数组,在访问时给出值?

时间:2016-09-26 01:14:19

标签: c++ arrays class dynamic

只是为了澄清这是我的编程任务的一部分我知道当人们讨论hw时人们如何讨厌,但我很难过,我现在对这个主题的理解需要澄清。

我需要创建一个名为UniqueVector的类,我必须使用动态数组创建它(不允许矢量)。数组中的所有数据必须是唯一的(没有重复)。现在最初它们都应该以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;
}

首先我的容量函数工作,如果它只是一个私有的T uniVector [3]而没有默认的构造函数,但现在它只返回1应该是3.

大小()从来没有在第一时间起作用,因为当我从未输入任何东西而不是大小时,我是如何创造价值的。

1 个答案:

答案 0 :(得分:1)

uniVector = new T[3]; // default constructor 
delete []uniVector;    

首先,此构造函数分配一个包含三个T s。

的数组

然后,立即删除此数组。

这没有任何意义。

此外,模板的其余部分假定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.

这应该足以让你入门。