返回一个指向std :: vector内的对象 [英] returning a pointed to an object within a std::vector
问题描述
我有一个非常基本的问题,返回一个向量的元素的引用。
I have a very basic question on returning a reference to an element of a vector .
有一个向量 vec
,用于存储类 Foo
。我想从这个向量访问一个元素。 (不想使用向量索引)。我应该如何编写方法 getFoo
这里?
There is a vector vec
that stores instances of class Foo
. I want to access an element from this vector . ( don't want to use the vector index) . How should I code the method getFoo
here?
#include<vector>
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
class Foo {
public:
Foo(){};
~Foo(){};
};
class B {
public:
vector<Foo> vec;
Foo* getFoo();
B(){};
~B(){};
};
Foo* B::getFoo(){
int i;
vec.push_back(Foo());
i = vec.size() - 1;
// how to return a pointer to vec[i] ??
return vec.at(i);
};
int main(){
B b;
b = B();
int i = 0;
for (i = 0; i < 5; i ++){
b.getFoo();
}
return 0;
}
推荐答案
为什么使用指针你可以返回一个引用?
Why use pointers at all when you can return a reference?
Foo& B::getFoo() {
vec.push_back(Foo());
return vec.back();
}
请注意,引用,指针和迭代器到
Note that references, pointers and iterators to a vector
s contents get invalidated if reallocation occurs.
还有成员资料公开(例如您的 vec
here)不是好的做法 - 最好根据需要为您的类提供访问方法。
Also having member data public (like your vec
here) isn't good practice - it is better to provide access methods for your class as needed.
这篇关于返回一个指向std :: vector内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!