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

会有一股神秘感。 提交于 2019-12-10 16:25:42

问题


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

回答1:


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 vectors contents get invalidated if reallocation occurs.

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.




回答2:


Why are you adding a new Foo object in your getFoo() method? Shouldn't you just be retrieving the i'th one?

If so, you can use something like

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

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




回答3:


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




回答4:


I'd suggest to use references 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();
};


来源:https://stackoverflow.com/questions/2711170/returning-a-pointed-to-an-object-within-a-stdvector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!