Returning a pointer to an object within std :: vector

I have a very simple question about returning a link to a vector element.

There is a vec vector that stores instances of the Foo class. I want to access an element from this vector. (do not want to use a vector index). How can I getFoo code 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; } 
+4
source share
4 answers

Why use pointers at all when you can return a link?

 Foo& B::getFoo() { vec.push_back(Foo()); return vec.back(); } 

Note that references, pointers, and iterators to vector content become invalid if redistribution occurs.

Also, having public member data (e.g. your vec here) is not good practice - it is best to provide access methods for your class as needed.

+2
source

Why are you adding a new Foo object to the getFoo () method? Shouldn't you just get the i-th?

If so, you can use something like

 Foo *getFoo(int i) { return &vec[i]; // or .at(i) } 

If you want to use the last element in a vector, use the back() method.

+2
source

Use back . You can do return &vec.back();

+1
source

I would suggest using links instead of pointers. Like this

 Foo& B::getFoo(){ vec.push_back(Foo()); return vec.back(); }; 

of course, you will also have to change the declaration for getFoo () in your class B:

 class B { public: vector<Foo> vec; Foo& getFoo(); }; 
+1
source

Source: https://habr.com/ru/post/1307981/


All Articles