c++结构体数组初始化
时间: 2023-11-18 19:54:31 浏览: 423
C++结构体数组初始化可以通过以下几种方式实现:
1. 在定义结构体数组时,直接初始化每个元素的值,例如:
struct city{
char name[20];
double population;
double housing;
double ave;
} cities = {{"Beijing", 2171.5, 748.3, 2.9}, {"Shanghai", 2418.3, 868.0, 2.8}, {"Guangzhou", 1308.4, 484.3, 2.7}};
2. 在定义结构体数组时,只初始化部分元素的值,例如:
struct city{
char name[20];
double population;
double housing;
double ave;
} cities = {{"Beijing", 2171.5}, {"Shanghai", 2418.3}, {"Guangzhou", 1308.4}};
//未初始化的元素将自动赋值为0
3. 在定义结构体数组后,逐个为每个元素赋值,例如:
struct city{
char name[20];
double population;
double housing;
double ave;
} cities;
cities = {"Beijing", 2171.5, 748.3, 2.9};
cities = {"Shanghai", 2418.3, 868.0, 2.8};
cities = {"Guangzhou", 1308.4, 484.3, 2.7};
阅读全文