我遇到了一个我以前没有见过的错误,它指出对事物的引用是模棱两可的。
我正在写一个小的测试程序来计算一个运行的中位数。随着列表的增长,它会重新计算中位数。在这种情况下,中位数表示列表中的中间数字(或上中间)。因此,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’的引用不明确”
发布于 2012-06-10 14:57:36
从我在尝试编译它时得到的编译器错误判断,名称空间std似乎定义了名称left和right,您也将它们用作变量名。编译器不能决定使用哪个定义,所以你得到了错误。正是由于这些原因,从名称空间导入所有内容都是不受欢迎的-您最好显式导入所需的名称或使用名称空间限定符。
在任何情况下,你的算法看起来都是不必要的复杂。为什么不只保留一个向量,当你得到一个新的数字时,将其插入其中,使用插入算法将该数字放在正确的索引中,然后返回该向量的中间上部元素?
发布于 2012-06-10 15:00:48
和是iostream中的标志。
只需重命名变量即可。
发布于 2012-06-10 15:05:43
这是一个很好的例子,说明了为什么#using namespace std不是一个好主意。还为std名称空间定义了left和right,现在出现了冲突。如果省略该行,而通过使用std::显式地指定它们名称空间来引用vector、string、cin和cout,就不会遇到这种冲突。
https://stackoverflow.com/questions/10966837
复制相似问题