Reputation: 69
#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;
}
In visual studio 2015,it shows,
but if I let ivec
to be a reference type(vector<int> & ivec
), it will work successfully.
Why?
The code is bad, bad, bad,,, so please you just focus on the question.
Upvotes: 0
Views: 197
Reputation: 1257
Because you're passing the vector by value copying it and making it != ivec.end()
undefined.
When you pass by value you're doing something like
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.
When you pass by reference you're doing something like
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
Or if you're more familiar with pointers
vector<int> v1 = {1,2,3,4,5,6,7};
vector<int>* v2 = &v1;
v1.end() == v2->end();
Upvotes: 0
Reputation: 310
Because iterator are relative to the container you get them from. Since you are passing your vector by value, it's like a second vector, and it doesn't make send to compare an iterator from the first vector and an iterator from the copied one.
Upvotes: 1