简体   繁体   English

使用指针访问 struct c++ 向量中的元素

[英]Accessing an element in a vector of struct c++ using pointers

Hi I'm new to c++ and wanted to ask a questions on how to access an element of struct inside a vector using pointers.嗨,我是 C++ 新手,想询问有关如何使用指针访问向量内的结构元素的问题。 lets say I have a 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;
???

} 

using the pointer ptr to the vector x how would I be able to access the first the age of the the first element stored in my vector of pets?使用指向向量 x 的指针 ptr 我如何能够访问存储在我的宠物向量中的第一个元素的第一个年龄? I am aware its easier to use我知道它更容易使用

x[0].age

but I wanted to acces the elements member using a pointer to a vector of struct.但我想使用指向结构向量的指针来访问元素成员。 Can anyone help?任何人都可以帮忙吗?

You need to dereference it first:您需要先取消引用它:

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

or或者

(*ptr)[0].age;

Live on Godbolt .住在Godbolt 上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM