怎样使用QVector装一个结构体并通过容器输出
时间: 2024-01-16 10:03:14 浏览: 53
首先,你需要定义一个结构体,例如:
```cpp
struct Person {
QString name;
int age;
};
```
然后,你可以创建一个 `QVector` 容器,并向其中添加几个 `Person` 结构体:
```cpp
QVector<Person> people;
people.append({"Alice", 25});
people.append({"Bob", 30});
people.append({"Charlie", 20});
```
最后,你可以使用迭代器遍历容器,并输出每个 `Person` 结构体的属性:
```cpp
for (auto it = people.begin(); it != people.end(); ++it) {
qDebug() << "Name:" << it->name << ", Age:" << it->age;
}
```
完整代码如下所示:
```cpp
#include <QDebug>
#include <QVector>
struct Person {
QString name;
int age;
};
int main() {
QVector<Person> people;
people.append({"Alice", 25});
people.append({"Bob", 30});
people.append({"Charlie", 20});
for (auto it = people.begin(); it != people.end(); ++it) {
qDebug() << "Name:" << it->name << ", Age:" << it->age;
}
return 0;
}
```
输出结果:
```
Name: "Alice" , Age: 25
Name: "Bob" , Age: 30
Name: "Charlie" , Age: 20
```