Reputation: 7319
This is the first time I'm trying to use pass by reference with vectors. I thought I did it correctly, but I get error: no viable overloaded '='
on the line that tries to assign a[0] = 5
void BubbleSort(vector<int> *a) {
int n = a->size(), numberOfSwaps = 0;
if (n > 0)
a[0]= 5;
}
int main(){
// input size and array
int n;
cin >> n;
vector<int> a(n);
for(int a_i = 0;a_i < n;a_i++){
cin >> a[a_i];
}
// sort
BubbleSort(&a);
// print
for (auto i = a.begin(); i != a.end(); ++i)
cout << *i << ' ';
return 0;
}
edit:
So now that I've been informed that I'm actually passing by pointer, my question is, should I be passing vectors by reference or by pointer, or does it not matter?
Upvotes: 0
Views: 185
Reputation: 118292
vector<int> *
is not a reference. vector<int> *
is a pointer.
Either change the function to take a reference as a parameter, or use (*a)[0]=5.
However, after you fix this program so that it compiles, when you run it, it will crash immediately as a result of undefined behavior due to accessing non-existent contents of the vector. You have other, multiple bugs to fix, in this code.
Upvotes: 4
Reputation: 2096
You're not passing by reference, you're passing a pointer. You need to dereference the pointer before you can access operator [].
(*a)[0] = 5;
Upvotes: 2