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

Creating an empty dynamic array in a class, giving values when accessed?

本文关键字:数组 动态 访问 创建 一个      更新时间:2023-10-16

只是澄清一下这是我的编程任务的一部分。我知道当人们问我如何时是多么讨厌,但是我被难住了,我目前对这个主题的理解需要澄清一下。

我需要创建一个名为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。

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。

这应该足够让你开始了