gpt4 book ai didi

c++ - 使用指针访问struct c++ vector 中的元素

转载 作者:行者123 更新时间:2023-12-02 10:22:59 27 4
gpt4 key购买 nike

嗨,我是C++的新手,想问一个问题,如何使用指针访问 vector 中的struct元素。
可以说我有一个结构:

struct pets{    //struct of pets
string name;
int age;
}

int main() {
pets a = {bolt, 2};
pets b = {crash, 3};

vector<pets> x;
x.push_back(a);
x.push_back(b);
vector<person> *ptr = &x;
???

}

使用指向 vector x的指针ptr,我如何能够访问存储在宠物 vector 中的第一个元素的第一个年龄?
我知道它更容易使用
x[0].age

但是我想使用指向struct vector 的指针来访问elements成员。
有人可以帮忙吗?

最佳答案

您需要先取消引用它:

ptr[0][0].age;
// ^^^ make sure you don't use >0 for the first one

要么
(*ptr)[0].age;

Godbolt

关于c++ - 使用指针访问struct c++ vector 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59235602/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com