在类中创建一个空的动态数组,在访问时给出值
Creating an empty dynamic array in a class, giving values when accessed?
只是澄清一下这是我的编程任务的一部分。我知道当人们问我如何时是多么讨厌,但是我被难住了,我目前对这个主题的理解需要澄清一下。
我需要创建一个名为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。
这应该足够让你开始了
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结