使用 for 循环 c++ 确定与数组中特定频率匹配的值的函数



对于任何明显的错误,请提前道歉,我在编程方面不是很熟练。我正在编写一个程序来确定数组中以用户搜索的确切频率出现的值的数量。例如,如果数据集包含数字 5,6,6,7,7,8,9,9,并且用户在数组中搜索频率为 2,因为数字 6、7 和 9 都恰好出现 2 次,它们与频率 2 匹配,因此程序将输出数组中有 3 个数字与频率 2 匹配, 并将列出与频率匹配的所有值一次。下面是我的程序中应该执行此计算的函数,但每次运行程序时,我都会得到一个值 0,用于与应该出现值的频率匹配的值。两个 for 循环是我的函数的要求,所以我需要它们正常工作,而不是使用不同的方法。我相信某些循环可能需要包含在其他循环中,但我无法完全适应它。任何帮助修复此功能将不胜感激。

short countOfFrequency (long data[], short dsize, long FreqNumbers[ ], short 
Frequency)
{
short i, j;
short count = 0;
short Value;
/*search above loop
(loop searches above each element in the array, if an element of the same 
value is found above the element, the loop terminates)*/ 
for (i=0; i<dsize; i++)
{
Value = data[i]; //the variable 'Value' is assigned to each element
for (j=0; j<i; j++)
{
break;
}
}
/*search below + count loop
(loop searches below each element in the array, if an element is found with 
the same value, the variable 'count' is increased by one)*/
for (j=i+1; j<dsize; j++)
{
if (Value==data[i])
{
count++;
}   
}
/*(If the count of a value matches the users desired frequency, that value
is stored in the FreqNumbers array)*/ 
if (count==Frequency)
{
FreqNumbers[dsize++] = Value;
}
return FreqNumbers[dsize];
}

首先,你应该使用向量而不是数组。 其次,如果您想获取数字列表,则应传递 FreqNumbers 作为参考。

#include<iostream>
#include<string>
#include<vector>
#include<map>
void countOfFrequency(std::vector<long> &data, std::vector<long> &FreqNumbers, short Frequency)
{
short count = 0;
short Value;
int dsize = data.size();
std::map<long, long > mapFreq; // first: for store each value of vector data, second for store it's counter
mapFreq.insert(std::pair<long, long>(data[0], 1));
for(int i = 1; i < dsize; i++)
{
auto &it = mapFreq.find(data[i]);
if(it != mapFreq.end())
{
it->second++;
}
else
{
mapFreq.insert(std::pair<long, long>(data[i], 1));
}
}
for(auto it : mapFreq)
{
if(it.second == Frequency)
FreqNumbers.push_back(it.first);
}
}

int main()
{
std::vector<long> data = { 5, 6, 6, 7, 7, 8, 9, 9 };
std::vector<long> FreqNumbers;
countOfFrequency(data, FreqNumbers, 2);
if(FreqNumbers.size())
{
for(auto number : FreqNumbers)
{
std::cout << number << ", ";
}
}
}

这实际上取决于您可以使用多少C++的细节。鉴于您现有的代码,使用C++没有任何独特之处。这可能是您的教师在课堂的这个阶段的意图。如果是这种情况,那么一个简单的手动排序例程,然后调用传递数据的函数,数据的大小,一个大小相等的数组来保存与请求的频率匹配的值以及要查找的频率,这是您可以获得的基本。例如

#include <iostream>
using namespace std;
int countfreq (int *data, int dsize, int *freqvals, int freq)
{
int last = *data,   /* set last to first value in data */
idx = 0,        /* index for freqvals to return */
seq = 1;        /* sequential values count */
if (freq <= 0 || freq > dsize)  /* is requested freq valid? */
return 0;
for (int i = 1; i < dsize; i++) {   /* loop 2nd value to end */
if (last == data[i])            /* if last == current */
seq++;                      /* increment sequential count */
else {  /* otherwise */
if (seq == freq)            /* sequential count == freq? */
freqvals[idx++] = last; /* add last value to freqvals */
seq = 1;                    /* reset sequential count 1 */
}
last = data[i];                 /* set last = current */
}
if (seq == freq)                    /* handle last value in data */
freqvals[idx++] = last;
return idx;     /* return freqvals index */
}
/* simple insertion sort */
void inssort (int *arr, int size)
{
for (int i = 0; i < size; i++)
for (int j = i - 1; j >= 0; j--)
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
else
break;
}
int main (void) {
int data[] = { 8, 9, 5, 6, 7, 6, 7, 9 },    /* unsorted data */
dsize  = sizeof data / sizeof *data,    /* number of elements */
*freqvals = new int[dsize],             /* allocate for freqvals */
freq  = 0,      /* frequency from user  */
nfreq = 0;      /* return from function */
for (int i = 0; i < dsize; i++)         /* zero the freqvals array */
freqvals[i] = 0;
inssort (data, dsize);                  /* sort data */
cout << "enter requested frequency: ";  /* prompt for frequency input */
if (!(cin >> freq)) {
cerr << "error: invalid input.n";
return 1;
}
/* call function saving return in nfreq */
if ((nfreq = countfreq (data, dsize, freqvals, freq))) {
cout << "the values matching requested frequency were: ";
for (int i = 0; i < nfreq; i++)     /* output csv */
if (i)
cout << ", " << freqvals[i];
else
cout << freqvals[i];
cout << "n";
}
else    /* otherwise, no values matched requested frequency */
cout << "no values appear with the requested frequency.n";
delete[] freqvals;  /* free allocated memory */
}

除了使用cin/coutnew/delete之外,该解决方案没有任何固有的C++,也可以用stdio.hstdlib.h而不是iostreamfgets/printfmalloc/free

如果您确实能够为阵列使用vector,则可以利用C++提供的细节。您可以简单地sort向量并简化函数参数,只需传递对data向量的常量引用和要查找的频率。您可以从函数返回一个向量,然后简单地测试返回向量的.size(),以确定是否找到了具有请求频率的任何值。逻辑是相同的,您必须使用的工具更方便一些,例如

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> countfreq (vector<int>& data, int freq)
{
vector<int> freqvals;       /* vector to return */
int dsize = data.size(),    /* size of initial check */
last = data.front(),    /* first value in data */
count = 0,              /* count flag for range loop */
seq = 1;                /* sequential values counted */
if (freq <= 0 || freq > dsize)  /* is freq valid? */
return freqvals;
for (auto& i : data) {      /* loop over data */
if (!count) {           /* if first iter, set flag continue */
count++;
continue;
}
if (last == i)          /* if current equals last */
seq++;              /* increment sequential count */
else {  /* otherwise */
if (seq == freq)    /* if sequential count == freq */
freqvals.push_back(last);   /* add value to vector */
seq = 1;            /* reset sequential count = 1 */
}
last = i;               /* update last */
}
if (seq == freq)            /* handle last value in data */
freqvals.push_back(last);
return freqvals;            /* return vector */
}
int main (void) {
vector<int> data = { 8, 9, 5, 6, 7, 6, 7, 9 };  /* unsorted data */
int freq;   /* the frequency of values to find */
sort (data.begin(), data.end());    /* sort data */
cout << "enter requested frequency: ";  /* prompt for freq input */
if (!(cin >> freq)) {
cerr << "error: invalid input.n";
return 1;
}
vector<int> frequency = countfreq (data, freq); /* call function */
if (frequency.size()) {             /* does return have elements? */
int count = 0;                  /* flag for output control */
cout << "the values matching requested frequency were: ";
for (auto& i : frequency)       /* loop over values in return */
if (count)
cout << ", " << i;      /* output as csv */
else {
cout << i;
count = 1;
}
cout << "n";
}
else    /* otherwise, handle no values returned */
cout << "no values appear with the requested frequency.n";
}

(注意:您提供的值以未排序的顺序用于data的内容)

无论您使用哪个,输出都是相同的,例如

示例使用/输出

$ ./bin/frequency
enter requested frequency: 0
no values appear with the requested frequency.
$ ./bin/frequency
enter requested frequency: 1
the values matching requested frequency were: 5, 8
$ ./bin/frequency
enter requested frequency: 2
the values matching requested frequency were: 6, 7, 9
$ ./bin/frequency
enter requested frequency: 3
no values appear with the requested frequency.

仔细查看,如果您有其他问题,请告诉我。有很多方法可以做到这一点,所以不要认为你仅限于这种方法。您可以随意将拼图的各个部分放在一起。

最新更新