I am a beginner in C++ stdlib. I learnt stdlib tutorials and I am implementing “number of connected components in Graph” using adjacency list created with stdlib lists. I wanted to know how to pass this array of list by reference to dfs function? Also, one of my frnd said that by default it will be passed by reference. Is it true? Please clarify. which of these is right?
for example:
- My array of list:
list<int> L[v]; - My function call:
dfs(L[v],k); - My function definition:
void dfs(list<int> List, int index); - My function prototype:
void dfs(list<int> L, int);
(or)
- My array of list:
list<int> L[v]; - My function call:
dfs(L,k); - My function definition:
void dfs(list<int> *L, int index); - My function prototype:
void dfs(list<int> *, int);
Not quite.
First of all, let’s forget about the
std::list; it’s just confusing matters.Pretend you’re passing an array of
intinstead:There are no references here, and C++ arguments are copied by default, but because arrays cannot be copied and because the name of an array decays to the name of a pointer to the first element in the array, you’re passing a [copy of a] pointer not the array itself.
In fact,
void foo(int[] x)is misleading syntactic sugar for the equivalent, and clearervoid foo(int* x).In particular note that — in both cases — the function
foodoes not know the dimension of the original array.This is kind of old-fashioned, though, and you can pass an actual reference to an array:
Now we can apply this same logic to arrays of
std::list:Anyway, mixing standard containers and arrays seems odd; prefer a
std::vectorover an array, or a wrapper around statically-allocated arrays (likestd::arrayor, previously,boost::array) if you really need the automatic storage duration for some reason.Also, your call syntax is wrong.
This passes a single list from the array of lists, and does so by value/copying.