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
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);
}
You can pass vector by reference just like this:
void do_something(int el, std::vector<int> &arr){
arr.push_back(el);
}
However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).
In order to achieve exactly the same result you should write:
void do_something(int el, std::vector<int> &arr){
if (arr.size() == 0) { // can't modify value of non-existent element
arr.push_back(el);
} else {
arr[0] = el;
}
}
In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).
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);
You don't need to use **arr, you can either use:
void do_something(int el, std::vector<int> *arr){
arr->push_back(el);
}
or:
void do_something(int el, std::vector<int> &arr){
arr.push_back(el);
}
**arr makes no sense but if you insist using it, do it this way:
void do_something(int el, std::vector<int> **arr){
(*arr)->push_back(el);
}
but again there is no reason to do so...
void do_something(int el, std::vector<int> **arr)
should be
void do_something(int el, std::vector<int>& arr)
{
arr.push_back(el);
}
Pass by reference has been simplified to use the &
in C++.