为什么我的函数不影响我在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;
}
答案 0 :(得分:1)
您要将向量中的每个元素反转两次。
第一次将0
放在n-1
上,然后当您按下i=n-1
时,将它们交换回来...
for (int i = 0; i < i1.size() / 2; ++i)