我正在尝试使用计数选择来实现运行中值算法并且卡住了。
要分析的序列称为'mySequence',我创建了2个全局变量;数据和计数的向量。数据是mySequence逐个传输的,count是每个元素的计数。
我担心我可能完全错了,或者错过了一个重要的步骤。
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
int maximum = 0;
vector<int> data;
vector<int> counts;
vector<int>::iterator it;
/*
* A Program that calculates and outputs the running median of a sequence of values
*/
/////////////////////////////////////////////////////////////////////////////
// This function prints the running median of a sequence of values past to it
/////////////////////////////////////////////////////////////////////////////
void runningMedian(int element, int k) { // vector<int> &data
maximum = data.size(); // finds how many data elements are to be processed
for (int i = 0; i <= maximum; i++) // this creates the counts for each element
{
counts[element] += 1;
}
int c = 0;
while (k >= 0) {
k -= counts[c++];
}
cout << c - 1;
}
/////////////////////////////////////////////////////////////////
// This main function uses test data to test the above functions
/////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {
int mySequence [] = {7, 9, 3, 8, 0, 2, 4, 8, 3, 9}; // test sequence
for (int i = 1; i <= 10; i++) counts.push_back(0); // This initialises the counts vector all to 0
/// prints out the sequence of the data ///
cout << "Sequence: ";
for (int i = 0; i < 10; i++) {
cout << mySequence[i] << " ";
}
cout << endl;
/// /// /// /// ///
cout << "Running Medians: ";
for (int i = 0; i < 10; i++) {
data.push_back(mySequence[i]); // puts sequence into vector 1 by 1
runningMedian(mySequence[i], (data.size() / 2));
cout << " ";
}
return 0;
}
答案 0 :(得分:0)
这看起来像是一个错误:
void runningMedian(int element, int k) { // vector<int> &data
maximum = data.size(); // finds how many data elements are to be processed
for (int i = 0; i <= maximum; i++) // this creates the counts for each element
{
counts[element] += 1;
}
当我看到for
循环迭代i=0; i<= ...
时,我会感到担心 - 实际上会迭代maximum+1
次,而不是maximum
次。 (惯用语是i=0; i< ...
。)这通常是缓冲区溢出或未初始化内存访问的快速途径 - 但由于在这种情况下你甚至没有使用i
,因此它不会产生这种影响。我认为你的意思是i
而不是element
- 否则为什么还要打扰循环呢?这可以在没有这样的循环的情况下重写:
counts[element] += (maximum + 1);
(你可以看到为什么我认为你可能打算用i
作为数组索引。)
我没有其他任何东西可以突出,但也许我也忽略了它。