调用插入排序函数后vector未变更的问题求助
Hey there, let's break down why your insertion sort isn't modifying the original vector as expected, and fix it step by step!
核心问题1:按值传递导致原容器未被修改
Your insertionSort function takes a vector<int> arr parameter—this is pass-by-value, which means the function gets a copy of your original vector. All the sorting work you do inside the function only affects this copy, not the vec you created in main(). That's why when you print vec after calling the function, it's still in the original order.
To fix this, you need to pass the vector by reference instead. Just add an ampersand (&) to the parameter:
void insertionSort(vector<int>& arr);
This tells the function to work directly with the original vector, not a copy.
核心问题2:未定义的变量引用
Inside your insertionSort function, you have this line:
for (auto i : vec) cout << i << endl;
But vec isn't defined in this function's scope—your parameter is named arr! This would actually cause a compile error. You should replace vec with arr here.
修正后的完整代码
Here's the fixed version of your code that works as expected:
#include <iostream> #include <vector> #include <cstdlib> #include <algorithm> using namespace std; void insertionSort(vector<int>& arr); // 改成传引用 int main() { vector<int> vec; const int arrSize = 5; for(int i = 0; i < arrSize; i++) { vec.push_back(rand() % 10); } cout << "Original vector:" << endl; for (auto i : vec) cout << i << " "; cout << endl; insertionSort(vec); cout << "Sorted vector:" << endl; for (auto i : vec) cout << i << " "; cout << endl; } void insertionSort(vector<int>& arr) { // 传引用 for(int i = 0; i < arr.size() - 1; i++) { int j = i + 1; while(j > 0 && arr[j - 1] > arr[j]) { swap(arr[j - 1], arr[j]); j--; } } cout << "Sorted inside function:" << endl; for (auto i : arr) cout << i << " "; // 用arr代替vec cout << endl; }
额外小提示
If you want consistent random numbers each time you run the program, you can seed the random generator with srand(time(0)); at the start of main()—otherwise, rand() will produce the same sequence every time you execute the code.
内容的提问来源于stack exchange,提问作者Ian Mckibben

