Reputation: 1
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
}
}
}
Upvotes: 0
Views: 137
Reputation: 1002
Although I prefer to change the source code as other answer. But, for this question, you can use ->at()
function to access the element in a vector pointer.
if(i<L->at(i)) {
temp = L->at(i+1);
L->at(i+1) = L->at(i);
L->at(i) = temp;
}
Upvotes: 0
Reputation: 310920
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] ) {
Upvotes: 0
Reputation: 67713
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.
Upvotes: 3