简体   繁体   English

将迭代器和向量传递给函数

[英]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. 当你复制它时,副本实际上是一个不同的迭代器,但是它存储了相同的值,所以它仍然指向同一个东西,就像指针一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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