I was trying to learn c++ and this piece of code keeps crashing again and again, any help is appreciated.
P.S. I am completely new to programming...
P.P.S I initially wrote this in Visual Studio, where it crashed too, with an access read violation
Well, I'm not sure what the goal is here. There is a lot of use of pointers where references would have been better.
As it stands, the bubbleSort() function could be written like this, making generous use of pointers wherever possible. Note that to access the elements within the array, the vector member function data() can be used, it returns a pointer to the start of the data. I don't recommend this, I only show it in order to get the current code to function correctly http://www.cplusplus.com/reference/vector/vector/data/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void Source1::bubbleSort(int n, vector<int>* a)
{
for (int p = 0; p<n; p++)
{
for (int j = p+1; j<n; j++)
{
if ( *((*a).data() +p) > *((*a).data() +j) )
swap( ((*a).data() + p), ((*a).data() + j) );
}
}
for (int k = 0; k<n; k++)
{
cout << *((*a).data() + k) << " ";
// cout << *(a->data() + k) << " "; // alternative notation
}
}
Now using references and not using pointers it might look like this: