用C++实现vector和person的迭代器功能,并能打印vector中多个person的年龄和姓名
时间: 2024-04-12 18:30:30 浏览: 11
下面是一个使用 C++ 实现 `vector` 和 `Person` 类的迭代器功能,并能打印 `vector` 中多个 `Person` 对象的年龄和姓名的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <string>
class Person {
private:
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}
std::string getName() const {
return name;
}
int getAge() const {
return age;
}
};
int main() {
std::vector<Person> people;
people.push_back(Person("Alice", 25));
people.push_back(Person("Bob", 30));
people.push_back(Person("Charlie", 35));
// 使用迭代器遍历 vector
std::vector<Person>::iterator it;
for (it = people.begin(); it != people.end(); ++it) {
std::cout << "Name: " << it->getName() << ", Age: " << it->getAge() << std::endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了一个 `Person` 类,其中包含了姓名和年龄两个成员变量,以及相应的访问函数。然后,我们创建了一个 `vector` 对象 `people`,并向其中添加了几个 `Person` 对象。
接下来,我们使用迭代器 `std::vector<Person>::iterator` 来遍历 `people` 中的每个元素。通过迭代器,我们可以访问每个 `Person` 对象的成员函数,从而获取其姓名和年龄,并打印输出。
运行上述代码,将会输出以下结果:
```
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
```
这样就实现了使用迭代器功能遍历 `vector` 中多个 `Person` 对象,并打印它们的年龄和姓名。