Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an iterator and vector to a function

Tags:

c++

vector

I have some function

void print_elem(const std::vector<int>::iterator it, const std::vector<int> &vec) {/*.....*/}

If I leave out that the vector is a reference to the original object, I get copies of the vector. Why doesn't the same hold true for the iterator? Why doesn't the iterator need to be a reference also?

For instance if I wanted to iterate through the vector, print each element and wanted to stop when I hit the end of the vector, unless I pass a reference to the vector the iteration just continuously iterates through the first vector copy. But if I pass through a reference the iteration goes through the original vector object. But why does the iterator not get copied the way the vector without reference does?

like image 617
Mars Avatar asked Aug 29 '13 18:08

Mars


People also ask

How do you pass a vector array to a function?

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.

Should iterators be passed by value or reference?

In general: If you pass a non- const reference, the caller doesn't know if the iterator is being modified. You could pass a const reference, but usually iterators are small enough that it gives no advantage over passing by value.

Can you pass a vector by reference?

A vector<int> is not same as int[] (to the compiler). vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor. So, you must use vector<int>& (preferably with const , if function isn't modifying it) to pass it as a reference.


1 Answers

The iterator models a pointer, and it most likely either is one, or contains one which points to the vector or its contents. When you copy it, the copy is in fact a different iterator, but it stores the same value, so it still points to the same thing, just like a pointer would.

like image 103
Benjamin Lindley Avatar answered Oct 06 '22 04:10

Benjamin Lindley