I am trying to implement a sorting algorithm where a vector is passed into a function and modified. However, when printing, the changes do not persist. Please ignore the fact that the full simpleSort is not implemented (goal is to implement quickSort). The question is related to vector behavior. Some resources I have checked out are: Passing vectors by reference Passing vector by reference Passing a vector by reference to function, but change doesn't persist
I think I am doing what they are saying but I am missing something fundamental. Below is an example of the code:
#include "stdafx.h"
#include <iostream>
#include <vector>
void simpleSort(std::vector<float>& theta , int);
void printArray(std::vector<float> & arr, int size)
int main()
{
std::vector<float> theta;
theta.push_back(10);
theta.push_back(-5);
theta.push_back(-3);
simpleSort(theta, theta.size()-1);
printf("Sorted array: \n");
printArray(theta, theta.size());
system("pause");
return 0;
}
void simpleSort(std::vector<float>& theta, int n)
{
for (int i = 0; i < n ; ++i)
{
if (theta[i] < theta[i + 1]) std::swap(theta[i], theta[i + 1]);
}
}
void printArray(std::vector<float> & arr, int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
As can be seen, the inputs are {10, -5, -3}. What I get when I print the result in main is {0, 0, 0}. But if I print the vector in the function itself, I get {-5, -3, 10}.
I thought I am correctly passing the vector in by reference by using "&", but I guess this is not the case.