简体   繁体   中英

Accessing vector in class

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.

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();

Create a public function called

std:vector getMyVec() {return my_vec;}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM