gpt4 book ai didi

c++ - 在 C 中转换 vector 的 C++ 实现

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:35 26 4
gpt4 key购买 nike

我用 C++ 编写了以下代码,但发现我必须将其转换为 C。我不是 C,甚至不是 C++ 程序员,请帮忙。

有人能帮我把这个方法改成 C 指令,特别是 vector 实现,下面不会编译我已经删除了复杂性以保持简单。感谢期待。

__declspec(dllexport) std::vector<MY_STRUCT> WINAPI ABC(char *strVal)
{
MY_STRUCT f;
std::vector<MY_STRUCT> list = std::vector<MY_STRUCT>();


while (*dddd)
{ /*do the following for every feature in license file*/

f.attrib_num = fi.attrib_num;
f.attrib_lic = fi.attrib_lic;

list.push_back(f);


} /* end while(conf) */

dddd++;
printf("\n");

} /* end while (*dddd) */

return flist;

}

最佳答案

这是 C 中动态结构数组的实现(也是用法)。您可以根据自己的结构调整它;我以前在code review上发过

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
int ID;
char * name;
} Student;

// array of structs
typedef struct
{
Student *array;
size_t used;
size_t size;
} Array;

void initArray(Array *a, size_t initialSize)
{
int i = 0;
// Allocate initial space
a->array = malloc(initialSize * sizeof(Student));

a->used = 0; // no elements used
a->size = initialSize; // available nr of elements

// Initialize all values of the array to 0
for(i = 0; i<initialSize; i++)
{
memset(&a->array[i],0,sizeof(Student));
}
}

// Add element to array
void addElement(Array *a, Student element)
{
int i = 0;
if (a->used == a->size)
{
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(Student));

// Initialize the last/new elements of the reallocated array
for(i = a->used; i<a->size; i++)
{
memset(&a->array[i],0,sizeof(Student));
}
}

// Copy name
a->array[a->used].name = (char*)malloc(strlen(element.name) + 1);
strcpy(a->array[a->used].name, element.name);

// Copy ID
a->array[a->used].ID=element.ID;

a->used++;
}

void freeArray(Array *a)
{
int i = 0;
// Free all name variables of each array element first
for(i=0; i<a->used; i++)
{
free(a->array[i].name);
a->array[i].name=NULL;
}

// Now free the array
free(a->array);
a->array = NULL;

a->used = 0;
a->size = 0;
}

int main(int argc, const char * argv[])
{

Array a;
Student x,y,z;

x.ID = 20;
x.name=malloc(strlen("stud1") + 1);
strcpy(x.name,"stud1");

y.ID = 30;
y.name=malloc(strlen("student2") + 1);
strcpy(y.name,"student2");

z.ID = 40;
z.name=malloc(strlen("student3") + 1);
strcpy(z.name,"student3");

// Init array, don't forget
initArray(&a, 5);

// Add elements
addElement(&a, x);
addElement(&a, y);
addElement(&a, z);

// Print elements
printf("%d\n", a.array[0].ID);
printf("%s\n", a.array[0].name);
printf("%d\n", a.array[1].ID);
printf("%s\n", a.array[1].name);
printf("%d\n", a.array[2].ID);
printf("%s\n", a.array[2].name);


// Free array
// don't forget
freeArray(&a);

free(x.name);
free(y.name);
free(z.name);

return 0;
}

关于c++ - 在 C 中转换 vector 的 C++ 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com