Home > Net >  Are STL vectors pass by reference/address?
Are STL vectors pass by reference/address?

Time:12-11

I was solving a recursion problem. While solving, I got stuck in a position where I am unable to figure this out:

#include<bits/stdc  .h>
using namespace std;

vector<int> Search(int arr[],int in, int n, int t, vector<int> &v){//v passed as ref.
    if(in == n){
        return v;
    }
    if(arr[in] == t){
        v.push_back(in);
    }
    return Search(arr, in 1, n, t, v);
}

int main(){
    int arr[] = {1, 2, 3, 4, 5, 4, 7, 4, 9, 4};
    vector<int> v;
    v = Search(arr, 0, 10, 4, v);
    for(int i = 0; i < v.size(); i  ){
        cout << v.at(i) << endl;
    }
    return 0;
}

In this code, I had passed the v as reference, but when I tried passing it without a reference then interestingly both of the codes worked.

#include<bits/stdc  .h>
using namespace std;

vector<int> Search(int arr[], int in, int n, int t, vector<int> v){
    if(in == n){
        return v;
    }
    if(arr[in] == t){
        v.push_back(in);
    }
    return Search(arr, in 1, n, t, v);
}

int main(){
    int arr[] = {1, 2, 3, 4, 5, 4, 7, 4, 9, 4};
    vector<int> v;
    v = Search(arr, 0, 10, 4, v);
    for(int i = 0; i < v.size(); i  ){
        cout << v.at(i) << endl;
    }
    return 0;
}

Can you explain why this happens?

CodePudding user response:

In the case of passing by reference you are pushing into the same vector that you pass in.

However when you pass by value you are pushing into a copy of the vector. But then you are returning the vector which returns the local copy, then you are assigning that (eventually) to the vector v in main. That's what makes it look like the code does the same thing even though it does not.

  • Related