Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing vector by reference

Tags:

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?

like image 688
user2252786 Avatar asked Apr 08 '13 22:04

user2252786


People also ask

Can vectors be passed by reference?

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.

How do you pass a vector call 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.

Is passing a vector by reference faster?

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.


2 Answers

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); } 
like image 95
Jon Purdy Avatar answered Oct 05 '22 02:10

Jon Purdy


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);  
like image 33
4pie0 Avatar answered Oct 05 '22 02:10

4pie0