C 中的问题在于您需要知道如何在结构中移动(即您需要知道类型)。 std::vector<T> 之所以如此运作,是因为它使用了模板(C++ 概念)。现在,也就是说,你可以尝试一些与你建议的稍有不同的东西。如果您不想使用任何数组,则可以存储泛型类型。但是,在检索和使用数据时,用户必须知道他或她期待什么样的数据。下面避免了数组(尽管在使用它们时存在一个潜在的更清洁的解决方案)并且有一个链接列表实现,它为您提供几乎与std::vector<T> 相同的灵活性(除了性能优势,因为这是一个具有O(n) 操作的链接列表一切(你可以聪明地把列表倒过来实现,也许,O(1) 插入,但这只是举例)
#include <stdio.h>
#include <stdlib.h>
typedef struct _item3_t
{
void *x, *y, *z;
struct _item3_t* next;
} item3_t;
typedef struct
{
item3_t* head;
} vec3_t;
void insert_vec3(vec3_t* vec, void* x, void* y, void* z)
{
item3_t* item = NULL;
item3_t* tmp = NULL;
int i = 0;
if(vec == NULL)
return;
item = malloc(sizeof(item3_t));
item->x = x;
item->y = y;
item->z = z;
item->next = NULL;
tmp = vec->head;
if(tmp == NULL) { // First element
vec->head = item;
} else {
while(tmp->next != NULL)
tmp = item->next;
tmp->next = item;
}
}
// This is one method which simply relies on the generic method above
void insert_vec3_float(vec3_t* vec, float x, float y, float z)
{
float* xv, *yv, *zv;
if(vec == NULL)
return;
xv = malloc(sizeof(float));
yv = malloc(sizeof(float));
zv = malloc(sizeof(float));
*xv = x;
*yv = y;
*zv = z;
insert_vec3(vec, xv, yv, zv);
}
void init_vec3(vec3_t* vec)
{
if(vec == NULL)
return;
vec->head = NULL;
}
void destroy_vec3(vec3_t* vec)
{
item3_t* item = NULL, *next = NULL;
if(vec == NULL)
return;
item = vec->head;
while(item != NULL) {
next = item->next;
free(item->x);
free(item->y);
free(item->z);
free(item);
item = next;
}
}
item3_t* vec3_get(vec3_t* vec, int idx)
{
int i = 0;
item3_t* item = NULL;
if(vec == NULL)
return NULL;
item = vec->head;
for(i = 0 ; i < idx && item != NULL ; ++i)
item = item->next;
return item;
}
void do_something(item3_t* item)
{
if(item == NULL)
return;
float x = *((float*)item->x);
float y = *((float*)item->y);
float z = *((float*)item->z);
// To do - something? Note, to manipulate the actual
// values in the vector, you need to modify their values
// at their mem addresses
}
int main()
{
vec3_t vector;
init_vec3(&vector);
insert_vec3_float(&vector, 1.2, 2.3, 3.4);
printf("%f %f %f\n", *((float*)vec3_get(&vector, 0)->x), *((float*)vec3_get(&vector, 0)->y), *((float*)vec3_get(&vector, 0)->z));
do_something(vec3_get(&vector, 0));
destroy_vec3(&vector);
return 0;
}
此代码应该可以直接编译。您在这里拥有的是一个链表,它是您的“向量”(特别是 vec3 结构)。列表中的每个节点(即std::vector<T> 意义上的每个元素)都有 3 个元素,它们都是 void 指针。因此,您可以在此处存储您希望的任何数据类型。唯一的问题是您需要为这些指针分配内存以指向并且在删除元素时,您需要释放该内存(请参阅vec3_destroy 方法以获取示例)。希望这有助于更多地了解这些 void 指针如何在您的情况下工作。
要检索数据,您将无法使用[] 表示法,但您可以以相同的方式使用vec3_get 方法。 do_something 方法是一个示例存根,您可以通过某种方式完成与您在 OP 中提到的类似的事情。