0
我想實現一個排序算法,其中一個向量傳入一個函數並進行修改。但是,打印時,更改不會持續。請忽略完整simpleSort未實現的目標(目標是實現quickSort)。問題與矢量行爲有關。我已簽出一些資源是: Passing vectors by reference Passing vector by reference Passing a vector by reference to function, but change doesn't persist通過引用修改向量不是持久
我覺得我做的,他們在說什麼,但我失去了一些東西根本。 下面是代碼的示例:
#include "stdafx.h"
#include <iostream>
#include <vector>
void simpleSort(std::vector<float>& theta , int);
void printArray(std::vector<float> & arr, int size)
int main()
{
std::vector<float> theta;
theta.push_back(10);
theta.push_back(-5);
theta.push_back(-3);
simpleSort(theta, theta.size()-1);
printf("Sorted array: \n");
printArray(theta, theta.size());
system("pause");
return 0;
}
void simpleSort(std::vector<float>& theta, int n)
{
for (int i = 0; i < n ; ++i)
{
if (theta[i] < theta[i + 1]) std::swap(theta[i], theta[i + 1]);
}
}
void printArray(std::vector<float> & arr, int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
如可以看到的,輸入爲{10,-5,-3}。我在主要打印結果時得到的是{0,0,0}。但是,如果我在函數本身中打印矢量,我會得到{-5,-3,10}。
我以爲我正確地通過參考使用「&」傳遞載體,但我想不是這種情況。
你是救世主!我非常專注於矢量部分,我從來沒有去質疑打印部分。我想我仍然在測試中使用整數。 – Victor