我遇到了一个我以前从未见过的错误,它指出对事物的引用是模棱两可的。
我正在编写一个计算运行中位数的小型测试程序。随着列表的增长,它会重新计算中位数。在这种情况下,中位数表示列表中的中间数字(或上中)。因此,7 的中位数是 7,7 和 9 的中位数是 9,7 3 和 9 的中位数是 7。
我正在用两个动态数组来完成这个(我希望)。最初,将第一个值设置为中位数,然后将输入的每个数字与当前中位数进行比较。中值用于计算两个数组之间的中间元素。
左侧数组用于所有小于中位数的值,右侧数组用于所有大于中位数的值。我使用插入排序来对每个数组中的数字进行排序(这在几乎排序的列表中非常有用)。
我只是不明白我遇到的错误以及我出错的地方。我对 C++ 相当陌生,所以我选择了一种更简单的方法来解决这个问题。
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> left;
vector<int> right;
int leftCount = 0;
int rightCount = 0;
void leftInsertionSort(int);
void rightInsertionSort(int);
void inputNumber(int, int);
int main(int argc, char** argv) {
int length = 0;
int value;
int median;
string input;
while (cin >> input) {
value = atoi(input.c_str());
inputNumber(value, median);
if (leftCount > rightCount) {
median = (((leftCount + rightCount) / 2) + 1);
cout << left[median];
} else {
median = (((leftCount + rightCount) / 2) + 1) - leftCount;
cout << right[median];
}
}
return 0;
}
void inputNumber(int value, int median) {
if (leftCount == 0 && rightCount == 0) {
left[0] = value;
median = value;
leftCount++;
} else
if (leftCount == 1 && rightCount == 0) {
right[0] = value;
if (left[0] > right[0]) {
right[0] = left[0];
left[0] = value;
}
median = right[0];
rightCount++;
} else
if (value < median) {
left[leftCount] = value;
} else {
right[rightCount] = value;
}
}
void leftInsertionSort(int lLength)
{
leftCount++;
int key, i;
for(int j = 1; j < lLength; j++)
{
key = left[j];
i = j - 1;
while (left[i] > key && i >= 0) {
left[i+1] = left[i];
i--;
}
left[i+1] = key;
}
}
void rightInsertionSort(int rLength)
{
rightCount++;
int key, i;
for(int j = 1; j < rLength; j++)
{
key = right[j];
i = j - 1;
while (right[i] > key && i >= 0) {
right[i+1] = right[i];
i--;
}
right[i+1] = key;
}
}
我似乎得到的错误是'错误:对'left'的引用不明确'