#include <iostream>
#include <vector>

using namespace std;

void factorial(vector<int> ivec, typename vector<int>::iterator iter)
{
    vector<int>::iterator it;
    for (it = iter; it != ivec.end(); it++)
         cout << *it << endl;
}

int main()
{
    vector<int> ivec;
    for (int i = 1; i < 8; i++)
        ivec.push_back(i);

    factorial(ivec, ivec.begin());

    return 0;
}


在visual studio 2015中,它显示

c&#43;&#43; - 容器作为函数参数-LMLPHP

但是如果让ivec作为引用类型(vector<int> & ivec),它将成功运行。

为什么?



代码是坏的,坏的,坏的,所以请您专注于这个问题。

最佳答案

因为您通过值复制传递向量并使it != ivec.end()不确定。

当您传递价值时,您正在做类似的事情

vector<int> v1 =  {1,2,3,4,5,6,7};
vector<int> v2 = v1;
//v2 is a copy of v1

v1.end() == v2.end();
//comparing end of different vectors don't have any sense.


当您通过引用时,您正在做类似的事情

vector<int> v1 = {1,2,3,4,5,6,7};
vector<int>& v2 = v1;
//v2 is a reference to v1, it's like an alias

v1.end() ==  v2.end();
//it makes sense because v2 is v1, not a copy


或者,如果您更熟悉指针

vector<int> v1 = {1,2,3,4,5,6,7};
vector<int>* v2 = &v1;

v1.end() ==  v2->end();

08-07 02:21