Accessing vector in class

2019-03-04 06:57发布

If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.

标签: c++ class vector
3条回答
狗以群分
2楼-- · 2019-03-04 07:22

Create a public function called

std:vector getMyVec() {return my_vec;}

查看更多
Explosion°爆炸
3楼-- · 2019-03-04 07:25

Depending on the semantics of your class, you may want to implement operator[]:

T& operator[](int i) {
  return my_vec[i];
}

This way you can user [] to access the contents of your vector:

MCL a;
a[0] = 3;
std::cout << a[0] << std::endl;

Note that this may be considered abuse of operator[] or bad practice, but it is up to the developer to judge if this construct fits in the class, depending on its semantics.

Also note that this solution does not provides a way to insert or delete elements from the vector, just access to the elements already there. You may want to add other methods to do these or to implement something like:

T& operator[](int i) {
  if(my_vec.size() < i)
    my_vec.resize(i+1);
  return my_vec[i];
}

Again, it is up to the semantics of your class and your usage pattern of it. This may or may not be a good idea.

查看更多
太酷不给撩
4楼-- · 2019-03-04 07:31

return it by const reference, or just by reference if you want to allow changing.

const std::vector<T> & getVector() const
{
    return vector;
}

usage:

const std::vector<T> &v = myClass.getVector();
查看更多
登录 后发表回答