Using normal C arrays I'd do something like that:
void do_something(int el, int **arr) { *arr[0] = el; // do something else }
Now, I want to replace standard array with vector, and achieve the same results here:
void do_something(int el, std::vector<int> **arr) { *arr.push_front(el); // this is what the function above does }
But it displays "expression must have class type". How to do this properly?
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By value. Pass By Reference.
Use the vector<T> &arr Notation to Pass a Vector by Reference in C++ std::vector is a common way to store arrays in C++, as they provide a dynamic object with multiple built-in functions for manipulating the stored elements.
A good rule of thumb is to pass anything as big as a pointer or smaller by value and anything bigger by reference. A std::vector is certainly better passed by const reference instead of making a copy.
You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector
does not have a push_front
member function. You can use the insert()
member function on vector
for O(n) insertion:
void do_something(int el, std::vector<int> &arr){ arr.insert(arr.begin(), el); }
Or use std::deque
instead for amortised O(1) insertion:
void do_something(int el, std::deque<int> &arr){ arr.push_front(el); }
If you define your function to take argument of std::vector<int>& arr
and integer value, then you can use push_back
inside that function:
void do_something(int el, std::vector<int>& arr) { arr.push_back(el); //.... }
usage:
std::vector<int> arr; do_something(1, arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With