Reputation:
Why doesn't my function influence the original vector I passed in main()
?
void swap2(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
void reverse_2(vector<int> &v1)
{
int j = v1.size() - 1;
cout << j << endl;
for (int i = 0; i != v1.size(); ++i)
{
swap2(v1[i], v1[j]);
j--;
}
}
int main()
{
vector<int>i1 = { 1,3,5,7,9 }, i2(i1.size());
i2 = reverse_1(i1);
for (int i = 0; i != i1.size(); ++i)
{
//cout << "First array"<<i1[i] << ","<<endl;
//cout << "Second array" << i2[i] << "," << endl;
}
reverse_2(i1);
cout << "First array changed" << endl;
for (int i = 0; i != i1.size(); ++i)
cout << i1[i] << ",";
cout << endl;
return 0;
}
Upvotes: 0
Views: 59
Reputation: 22023
You are inverting every element in your vector twice.
The first time you put say 0
to n-1
, then when you hit i=n-1
, you swap them back...
for (int i = 0; i < i1.size() / 2; ++i)
Upvotes: 1