简体   繁体   English

访问 class 中的向量

[英]Accessing vector in class

If I have a vector as a private member in my class, what's the best way to access it?如果我在 class 中有一个向量作为私有成员,那么访问它的最佳方式是什么? For example, take the following simple class比如下面这个简单的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?访问 my_vec 的最佳方式是什么? Specifically, I would like to use a getter function to access it.具体来说,我想使用吸气剂 function 来访问它。

return it by const reference, or just by reference if you want to allow changing.通过 const 引用返回它,或者如果您想允许更改,则仅通过引用返回。

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

usage:用法:

const std::vector<T> &v = myClass.getVector();

Create a public function called创建一个名为的公共 function

std:vector getMyVec() {return my_vec;} std:vector getMyVec() {return my_vec;}

Depending on the semantics of your class, you may want to implement operator[]:根据 class 的语义,您可能需要实现 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.请注意,这可能被认为是滥用 operator[] 或不良做法,但由开发人员根据其语义判断此构造是否适合 class。

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.同样,这取决于您的 class 的语义及其使用模式。 This may or may not be a good idea.这可能是也可能不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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