[英]Accessing an element in a vector of struct c++ using pointers
嗨,我是 C++ 新手,想詢問有關如何使用指針訪問向量內的結構元素的問題。 假設我有一個結構:
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;
???
}
使用指向向量 x 的指針 ptr 我如何能夠訪問存儲在我的寵物向量中的第一個元素的第一個年齡? 我知道它更容易使用
x[0].age
但我想使用指向結構向量的指針來訪問元素成員。 任何人都可以幫忙嗎?
您需要先取消引用它:
ptr[0][0].age;
// ^^^ make sure you don't use >0 for the first one
或者
(*ptr)[0].age;
住在Godbolt 上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.