2016 - 2024

感恩一路有你

在C/C 中使用vector存放结构体类型变量

浏览量:4380 时间:2024-04-01 14:58:09 作者:采采

在C/C 中,常常需要使用容器来存储结构化数据,其中vector是一个常见且方便的选择。在vector中存放结构体struct类型的变量有两种主要方法。第一种是存放结构体类型变量的副本,第二种是存放指向结构体类型变量的指针。

存放结构体类型变量的副本

```cpp

include

include

include

typedef struct student {

char school_name[100];

char gender;

int age;

bool is_absent;

} StudentInfo;

typedef std::vector StudentInfoVec;

void print(StudentInfoVec *studentinfovec) {

for (int j 0; j < (*studentinfovec).size(); j ) {

std::cout << (*studentinfovec)[j].school_name << " ";

std::cout << (*studentinfovec)[j].gender << " ";

std::cout << (*studentinfovec)[j].age << " ";

std::cout << (*studentinfovec)[j].is_absent << std::endl;

}

}

int main() {

StudentInfo micheal {"Micheal", 'm', 18, false};

StudentInfo cherry {"Cherry", 'f', 16, true};

StudentInfoVec studentinfovec;

studentinfovec.push_back(micheal);

studentinfovec.push_back(cherry);

print(studentinfovec);

system("pause");

return 0;

}

```

存放指向结构体类型变量的指针

```cpp

include

include

include

typedef struct student {

char* school_name;

char gender;

int age;

bool is_absent;

} StudentInfo;

typedef std::vector StudentInfoPtrVec;

void print(StudentInfoPtrVec* studentinfoptrvec) {

for (int j 0; j < (*studentinfoptrvec).size(); j ) {

std::cout << (*studentinfoptrvec)[j]->school_name << " ";

std::cout << (*studentinfoptrvec)[j]->gender << " ";

std::cout << (*studentinfoptrvec)[j]->age << " ";

std::cout << (*studentinfoptrvec)[j]->is_absent << std::endl;

}

}

int main() {

StudentInfoPtrVec studentinfoptrvec;

char* p_char_1 NULL;

p_char_1 new char[100];

strcpy(p_char_1, "Micheal");

StudentInfo* p_student_1 new StudentInfo;

p_student_1->school_name p_char_1;

p_student_1->gender 'm';

p_student_1->age 18;

p_student_1->is_absent false;

studentinfoptrvec.push_back(p_student_1);

char* p_char_2 NULL;

p_char_2 new char[100];

strcpy(p_char_2, "Cherry");

StudentInfo* p_student_2 new StudentInfo;

p_student_2->school_name p_char_2;

p_student_2->gender 'f';

p_student_2->age 16;

p_student_2->is_absent false;

studentinfoptrvec.push_back(p_student_2);

print(studentinfoptrvec);

delete p_char_1;

delete p_student_1;

delete p_char_2;

delete p_student_2;

system("pause");

return 0;

}

```

通过以上两种方式,我们可以灵活地在C/C 中使用vector来存放结构体类型的变量,并根据实际需求选择适合的存储方式。

版权声明:本文内容由互联网用户自发贡献,本站不承担相关法律责任.如有侵权/违法内容,本站将立刻删除。