我正在尝试完成一个程序来执行快速选择算法并使用向量,因为元素是随机生成的。当我现在运行我的代码时,我得到了错误:
undefined reference to quickSelect(int, std::vector<int, std::allocator<int> >*)
当我从向量声明和引用中删除所有“&”和“*”符号,并尝试在我的 quickSelect 函数中打印向量的值时,我得到一堆不准确的随机值。当我在主函数中打印向量的值时,我得到了正确的值。这让我相信当我将向量传递给函数时发生了一些事情。如何将正确的值传递给函数 quickSelect?
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <ctime>
#include <vector>
using namespace std;
int k, l, p, i, x, j, res;
int val;
int Pivot1 = rand()%50;
int Pivot2 = rand()%50;
int quickSelect(int, vector<int>* arr);
vector<int> arr;
int main(){
/*
cout << "p: ";
cin >> p;
cout << "k: ";
cin >> k;
cout << "l: ";
cin >> l;
*/
l = 50;
vector<int> arr(l);
srand(time(0));
for (i=0; i<l; i++){
x = (rand()%50);
arr[i] = x;
}
for (i=0; i<l; i++){
for (j=i; j<l; j++){
if (j != i){
if (arr[i] == arr[j]){
val = true;
}
}
if (val == true){
arr[i] = arr[i]+1;
}
}
val = false;
}
quickSelect(2, &arr);
}
int quickSelect(int k, vector<int> &arr){
static int counter = 0;
counter++;
vector<int> small;
vector<int> large;
int Pivot1 = arr[rand()%50];
l = 50;
for (i=0; i<l; i++){
cout << &arr[i] << endl;
}
// cout << arr[0] << endl;
// cout << arr[16] << " " << "life" << endl;
for(int i=0; i<l; i++){
if (arr[i] < Pivot1) {
small.push_back(arr[i]);
}
if (arr[i] > Pivot1) {
large.push_back(arr[i]);
}
}
if(k <= large.size()) {
return quickSelect(k, large);
} else if (k > large.size() + 1){
return quickSelect((k - large.size() - 1), small);
} else {
return Pivot1;
}
return 0;
}