Home > OS >  Access an element of a vector given the vector's pointer
Access an element of a vector given the vector's pointer

Time:06-14

I am trying to create a sorting function with the parameters being a pointer of a list and I am trying to access an element of the given list. Hopefully this code speaks for the problem better than I can:

void bubbleSort(std::vector<int> *L) {
    unsigned int i = 0; int temp;
    while(isSorted(*L)) {
        if(i==L->size()-1) {
            i = 0;
        }
        if(i<L[i]/*<-ERROR here.*/) {
            temp = L[i 1]; // ERROR HERE
            L[i 1] = L[i]; // ERROR HERE
            L[i] = temp; // ERROR HERE
        }
    }
}

CodePudding user response:

You don't need to painfully dereference every individual use of L (and indeed doing so is error-prone, as you've demonstrated by missing one in your answer).

Instead, just write:

void bubbleSort(std::vector<int> *Lptr) {
  auto &L = *Lptr;

and keep the rest of the code the same.


NB. It would be even better to change the function itself, to

void bubbleSort(std::vector<int> &L) {

as it should have been written in the first place, but I'm assuming there's some artificial reason you can't do that.

CodePudding user response:

The function accepts a pointer to an object of type std::vector<int>.

void bubbleSort(std::vector<int> *L) {

To access the original vector using the pointer, you can write either *L or L[0]. That is, both expressions yield an lvalue reference of type std::vector<int> & to the vector.

To get the i-th element of the vector using the subscript operator through the pointer, you can write either (*L)[i] or L[0][i],

However, in this if statement:

if(i<L[i]/*<-ERROR here.*/) {

You are trying to compare the variable i of type unsigned int to the object L[i] of type std::vector<int>. When i is not equal to 0, this yields a non-existent object of the vector type.

It seems you mean something like the following instead:

if ( (*L)[i] < (*L)[i 1] ) {

or:

if ( L[0][i] < L[0][i 1] ) {

or, vice versa:

if ( L[0][i 1] < L[0][i] ) {

Depending on whether the vector is sorted in ascending or descending order.

Pay attention to the fact that there is no sense in declaring the parameter as a pointer to a std::vector<int>. The function would be much clearer and readable if it accepted the vector by reference instead:

void bubbleSort(std::vector<int> &L) {

In this case, the if statement would look like this:

if ( L[i] < L[i 1] ) {
  • Related