【发布时间】:2020-06-24 23:18:35
【问题描述】:
这是我的第一篇文章,希望我没有做错任何事。 我正在尝试编写一个程序来找到在其中出现 k 次的向量的第一个值。
例如,给定此矢量和k = 3:1 1 2 3 4 4 2 2 1 3
我会看到 2 作为输出,因为 2 是第一个到达第三次出现的数字。
以下代码是我尝试运行的,但不知何故输出不正确。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vettore;
int k;
int a,b,i;
int occ_a;
int occ_b;
cout<< "Write values of vector (number 0 ends the input of values)\n";
int ins;
cin>>ins;
while(ins)
{
vettore.push_back(ins); //Elements insertion
cin>>ins;
}
cout<<"how many occurrences?\n"<<endl;;
cin>>k;
if(k>0)
{
int i=0;
b = vettore[0];
occ_b=0;
while(i< vettore.size())
{
int j=i;
occ_a = 0;
a = vettore[i];
while(occ_a < k && j<vettore.size())
{
if(vettore[j]== a)
{
occ_a++;
vettore.erase(vettore.begin() + j);
}
else
j++;
}
if(b!=a && occ_b < occ_a)
b = a;
i++;
}
cout << b; //b is the value that reached k-occurrences first
}
return 0;
}
时间已经过去,但我没有能够解决它。
感谢您的帮助!
【问题讨论】:
-
这是一个很好的问题,可以用来练习使用开发环境附带的调试器。用最少的优化和任何可用的调试选项编译程序,然后在调试器中运行程序。使用调试器逐行执行程序,并密切关注正在使用的变量。一旦你看到程序做了你没想到的事情,停下来找出它发生的原因。通常意外是一个错误。 span>
-
旁注:看看
std::map和std unordered_map和map<int, int>可以很短地解决频率计数类型的问题。 -
旁注:在 C++ 中,我们在使用变量时声明变量,而不是在其作用域的顶部
-
为什么会得到
2作为输出?1也出现 3 次,在数组中出现在2之前。 -
@0x499602D2 2 的第 k 次发生在 1 的第 k 次之前。:) 这就是我对分配的理解。
标签: c++ algorithm vector computer-science