简体   繁体   中英

What does this code mean ? did this transfer a vector to an array?

I have the code of a function below, that takes as parameter a pivot integer and a vector A. I would like to know what this auto& A_ref = *A; means. I am not familiar with &auto. Did this make the vector pointer an array ? and what is the value of doing such a thing

void function1(vector<int>* A, int pivot_index)
{
    auto& A_ref = *A;
    int pivot = A_ref[pivot_index];
}

It seems that the author of the code does not know how to use operator [] with pointers:) or he wanted to simplify the access to the operator. So instead of

int pivot = ( *A )[pivot_index];

or

int pivot = A->operator[]( pivot_index );

he wrote

auto& A_ref = *A;
int pivot = A_ref[pivot_index];

*A has type std::vector<int> . So statement

auto& A_ref = *A;

can be written like

std::vector<int> & A_ref = *A;

auto allows the compiler to deduce the type of the object from the initializer expression. For example

int x = 10;
auto y = x;

Here y has the same type as its initializer expression x . If you do not want to define a new object but want to define a reference to already existent object you can write for example

int x = 10;
auto &rx = x;

Take into account that class std::vector has overloaded subscript operator [] . So you can access elements of a vector the same way as elements of an array.

auto is expanded by the compiler to match the rvalue that is assigned . it will be expand to vector<int>

so the first line is equal to vector<int>& A_ref = *A

anyway , this code is not the safest or intuitive. you could simply write :

void function1(vector<int>& A, int pivot_index)
{
    int pivot = A[pivot_index];
}

According to http://en.cppreference.com/w/cpp/language/auto this auto "Specifies that the type of the variable that is being declared will be automatically deduced from its initializer." So basically I think this "auto" is a matter of comfort in this case.

*A is returning the content of the pointer, ie, the vector, and it is being hold by A_ref .

A_ref[pivot_index] is simply accessing to the vector.

If you wished to access the vector without A_ref , you should to something like

(*A)[pivot_index]

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