1028 人口普查C++
时间: 2025-01-15 18:17:48 浏览: 41
### 关于人口普查的C++编程示例
在处理人口普查数据时,通常会涉及到大量的数据分析操作。下面提供一段简单的C++代码用于模拟基本的人口普查数据收集和统计功能。
#### 定义人口普查记录结构体
为了存储个人的信息,在此定义了一个`PersonRecord`结构体来保存每个人的年龄、性别和地区信息:
```cpp
#include <iostream>
#include <vector>
#include <string>
struct PersonRecord {
std::string name;
int age;
char gender; // 'M' for male, 'F' for female
std::string region;
PersonRecord(std::string n, int a, char g, std::string r) :
name(n), age(a), gender(g), region(r) {}
};
```
#### 创建并填充人口普查数据库
接下来创建一个函数用来初始化一组虚拟的人口普查数据,并将其存入到容器中以便后续分析:
```cpp
std::vector<PersonRecord> createPopulationData() {
return {
{"Alice", 30, 'F', "North"},
{"Bob", 25, 'M', "South"},
{"Charlie", 45, 'M', "East"},
{"Diana", 38, 'F', "West"}
};
}
```
#### 统计特定条件下的统计数据
这里展示如何计算某个区域内男性人数以及平均年龄的例子:
```cpp
void analyzeDemographics(const std::vector<PersonRecord>& population) {
double totalAge = 0;
size_t countMaleInRegion = 0;
const auto& targetRegion = "East"; // 可以更改为其他地区
for (const auto& person : population) {
if (person.region == targetRegion && person.gender == 'M') {
++countMaleInRegion;
totalAge += person.age;
}
}
if (!countMaleInRegion) {
std::cout << "No males found in the specified region." << std::endl;
} else {
std::cout << "Number of males in '" << targetRegion << "' is "
<< countMaleInRegion << ". Average age: "
<< static_cast<double>(totalAge)/countMaleInRegion << "." << std::endl;
}
}
int main() {
auto popData = createPopulationData();
analyzeDemographics(popData);
return 0;
}
```
这段程序展示了如何利用C++中的标准库特性(如字符串处理、向量容器等),实现对人口普查数据的基本管理和查询功能[^1]。
阅读全文
相关推荐

















