通过引用传递时访问 std::vector 的元素

accessing elements of std::vector when passing by reference

有没有更简单的方法来访问通过引用传递的向量元素?这会起作用,但似乎过于复杂。提前感谢您的帮助!!!

#include <iostream>
#include <vector>
using namespace std;

void my_func(std::vector<int> * vect){
    // this will not work
    cout << *vect[2] << endl;
    // this will work
    cout << *(vect->begin()+2) << endl;
}

int main(){
    std::vector<int> vect = {1,3,4,56};
    my_func(&vect) ;
    return 0;
}

在您的示例中,您将 指针 传递给向量。

要通过引用传递:

void my_func(std::vector<int>& vect) ...

然后就很简单了 vect[index] 来访问一个元素。

并且通常当您通过引用传递容器时,您还希望指定 const 以免意外修改其中的内容。当然,除非你是故意的。