'What is the time complexity of passing a Vector of size n to another function by passing by value and passing by reference?

void fun(vector<int>vec)
{
   some code
}
int main()
{
   int n = 5;
   vector<int>avec(n);
   fun(avec);
}

What is the time complexity of passing a Vector of size n to another function by passing by value and passing by reference? What is the time complexity of this code passing a vector only one time?



Solution 1:[1]

Passing a std::vector of size N to a function by value obviously has a linear complexity O(n), since it involves copying N objects. Passing by reference has complexity O(1), since in fact only the address of the std::vector is passed to the function, regardless of its size.

It is worth noting that the situation is different with returning a std::vector from a function, in this case, returning by value has a complexity of O(1), since in this case the compiler either uses copy elision , if it is permitted, or the move constructor. Both has O(1) compexity.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1