【发布时间】:2014-06-28 15:17:34
【问题描述】:
我正在尝试通过向量上的链表执行某些操作。
我们得到了一个结构体类型向量
typedef struct{
int *array; // a pointer to vector's storage
int size; // the current number of elements in the vector
int cap; // the current capacity of the vector;
int init_cap; // the initial capacity the vector was initialised with.
} vector;
现在,我想创建一个函数,它接收指向向量结构的指针,并使用给定的容量对其进行初始化。所有字段都将被初始化。我想使用链表来做到这一点。
这是我的代码
#include <iostream>
using namespace std;
typedef struct node {
int *array; // a pointer to the vector's storage
int size; // the current number of elements in the vector
int cap; // the current capacity of the vector
int init_cap; // the initial capacity the vector was initialised with
node *next;
} vector;
node *head = NULL;
我可以像我在上面编写的代码中尝试的那样从向量结构中创建节点吗?
void vector_init(vector *v, int capacity){
//initialising the vector with the given capacity
v->size = capacity;
v->cap = capacity;
v->init_cap = capacity;
//linked list with nodes created and values initialised
node *temp, temp2;
temp = head;
temp = new node;
temp->size = capacity;
temp->cap = capacity;
temp->init_cap = capacity;
temp->next = temp2
temp2 = new node;
temp2->size = capacity;
temp2->cap = capacity;
temp2->init_cap = capacity;
temp2->next = NULL;
}
我是否创建了链表并正确初始化了值?如果我们不创建临时点 temp 和 temp2,而只是使用 v->size 等来初始化字段,那会不会使它成为一个链表?
【问题讨论】:
-
typedef struct,认真的吗?谁教你这些东西? -
这个问题更适合Code Review,只要您的代码没有遇到任何特殊问题。
-
我建议不要将名称
vector用于您自己的数据结构,因为这可能会与std::vector类冲突,尤其是因为您声明了using namespace std;。 -
好的,如果我们删除 using namespace std;然后使用向量作为数据结构,可以吗? @djikay
-
令人难以置信的是为什么一个所谓的“C++ 讲师”会将用户定义的类型称为
vector。
标签: c++ vector linked-list