【发布时间】:2021-08-28 06:48:41
【问题描述】:
我有一个类,我想编写一个通用的排序列表,我们可以将它与该类一起使用:
class A
{
int n;
public:
A(int n):n(n){}
};
这就是我想如何做我的排序列表类
template <class T>
class SortedList
{
T* data;
int size;
int max_size;
void expand();
static const int EXPAND_RATE=2;
static const int INITIAL_SIZE=10;
public:
SortedList();
};
template <class T>
SortedList<T>::SortedList():data(new T[INITIAL_SIZE]),size(0),max_size(INITIAL_SIZE){}
// ^^^ here we need a T()
现在的问题是 A 类没有像这样的 c'tor A()
有没有人知道如何在不需要A() 的情况下编写 sortedlist 类??
PS:有些人建议用T data 和next 做节点,但我看不出我该怎么做,这有什么帮助?因为我们仍然需要T()
编辑:我现在尝试这样做:
template <class T>
class SortedList
{
T** data;
// ^^
int size;
int max_size;
void expand();
static const int EXPAND_RATE=2;
static const int INITIAL_SIZE=10;
public:
SortedList();
};
template <class T>
SortedList<T>::SortedList():data(new T*[INITIAL_SIZE]),size(0),max_size(INITIAL_SIZE){}
现在我遇到了这个函数的另一个问题:
void SortedList<T>::insert(const T& object)
{
if(size>=max_size)
{
expand();
}
int index=0;
for(int i=0;i<size;i++)
{
T item=*data[i];
// when I try to print item nothing goes out
if(item<object)
// ^^^ here I get a segmentation fault
{
continue;
}
index=i;
break;
}
size++;
for (int i = size-1; i >index; i--)
{
data[i]=data[i-1];
}
T Item(object);
T* ptr= &Item;
data[index]=ptr;
//when I print *data[index] it does get printed perfectly
}
【问题讨论】:
-
为什么不使用
std::vector? -
你想要一个列表还是一个数组/向量?
-
@Jarod42 这是不允许的
-
@Jarod42 我基本上想写一个通用列表,但不能使用任何 STL
-
所以确实要使用 Node(您不必处理容量问题,这是有问题的东西)。
标签: c++ list class generics constructor