std :: vector的访问元素

jma*_*erx 0 c++ vector

我有一个函数,我提供了一个指向std :: vector的指针.

我想让x = to vector [element]但是我遇到了编译器错误.

我正在做:

void Function(std::vector<int> *input)
{
   int a;
   a = *input[0];
}
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?谢谢

GMa*_*ckG 8

应该:

void Function(std::vector<int> *input)
{
    // note: why split the initialization of a onto a new line?
    int a = (*input)[0]; // this deferences the pointer (resulting in)
                         // a reference to a std::vector<int>), then
                         // calls operator[] on it, returning an int.
}
Run Code Online (Sandbox Code Playgroud)

否则,你已经得到了*(input[0]),这是*(input + 0),这是*input.当然,为什么不这样做:

void Function(std::vector<int>& input)
{
    int a = input[0];
}
Run Code Online (Sandbox Code Playgroud)

如果您不修改input,请将其标记为const:

void Function(const std::vector<int>& input)
{
    int a = input[0];
}
Run Code Online (Sandbox Code Playgroud)