6

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?

4

1 回答 1

10

迭代器模拟一个指针,它很可能一个,或者包含一个指向向量或其内容的指针。当你复制它时,它实际上是一个不同的迭代器,但它存储了相同的值,所以它仍然指向同一个东西,就像指针一样。

于 2013-08-29T18:14:36.987 回答