简体   繁体   中英

Passing an iterator and vector to a function

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM