Reputation: 102
It's said that when we pass an array to a function then only copy of that array is passed to the function. If we modify the array inside that function then original array would also be affected. So will case 1 take equal memory or it would consume significantly higher memory when compared to case 2 ?
//Case 1:-
int sum(vector<int> v)
{
...
}
//Case 2:-
int sum(vector<int> &v)
{
...
}
Upvotes: 1
Views: 124
Reputation: 801
You're passing a std::vector
, not an Array. The first case will take a copy of that vector (copying all elements to a new instance of std::vector<int>
), while the second will just take a reference to the original vector.
It's quite obvious that the second case will be more efficient (both performance and memory wise) than the first one, because no copying will be done and you don't end up having two vectors.
But even better (not for performance but code design) would be
int sum(const std::vector<int> &v)
{
...
}
Because you're not modifying the vector.
PS: Why is "using namespace std;" considered bad practice
Upvotes: 5