向列表中添加新元素
Add new element to the list
我有一个单链表,我想在这个结构中添加一个新元素。
在过程代码中,我将创建结构,头部指针指向NULL。这是我在oo代码中解决这个问题的方法:
typedef struct a {
int element;
struct a *next;
} a;
typedef struct b {
int element;
struct b *next;
} b;
class Foo {
a *a; // head for a structure = NULL at the beginning
b *b; // head for b structure = NULL at the beginning
接下来我要做的是检查列表是否为空,如果是,设置head指向新创建的第一个元素。
执行此操作的函数应该是template,因为我想将我拥有的任何结构传递给它。所以:
template <class T> void Addition_Struct::add(T head)
{
if(head == NULL)
{
head = (T*)malloc(sizeof(T));
head->next = NULL;
}
}
这时出现了几个问题。我猜T应该是一个结构的类型,头部指针(NULL当前)。编译器在malloc行cannot convert "a**" to "a*"
抛出错误。怎么了?
示例函数调用将是:
add(this->a);
您混淆了模板函数中T
的含义。
在您的示例调用add(this->a);
中,您将参数考虑为指向结构体的指针。
但是你的函数head = (T*)malloc(sizeof(T));
认为T
是结构类型。不是指针
修改模板声明,明确T
是指向的类型。
template <class T> void Addition_Struct::add(T * head)
相关文章:
- 静态堆栈函数不会 1) 输入第一个元素 2)添加新元素时识别旧元素
- 在二叉搜索树中插入新元素
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- 将新元素添加到列表中,并返回对该元素的引用?
- 如果键不存在,使用 [] 运算符访问 STL Map 元素会添加新元素
- 向 std::list 添加新元素的复杂性
- 是否可以使用OpenMP并行化一个列表,该列表可以在每次迭代中添加新元素
- 在指向对象的指针的动态数组上插入新元素
- c++ 向量push_back移动新元素
- 新元素将在std :: set中插入哪里
- 编写链接函数的更短/更有效的方法,该函数按字典顺序添加新元素
- 在C++中,如何在没有新元素且不单独声明单个元素的情况下创建"std::initializer_list<base *>"?
- 在unordered_map/unordered_set中插入/放置新元素时的提示
- 将新元素添加到动态数组C
- 插入新元素时结束迭代器会获得更新
- 将新元素推送到函数指针映射中 "inline" ?
- 自定义容器在保留空间时不必要地创建新元素实例
- 删除前面元素并将新元素添加到最小堆 (std::p riority_queue)
- 2D-Array 会在存储新元素时删除元素本身
- 创建新元素崩溃后,tinyxml2 xmldocument parse