returning a pointed to an object within a std::vector

Posted by memC on Stack Overflow See other posts from Stack Overflow or by memC
Published on 2010-04-26T04:32:42Z Indexed on 2010/04/26 4:43 UTC
Read the original article Hit count: 169

Filed under:
|
|

I have a very basic question on returning a reference to an element of a vector .

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;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about beginner