【问题标题】:C++ code not working for multiple test cases [closed]C ++代码不适用于多个测试用例[关闭]
【发布时间】:2022-11-14 19:10:25
【问题描述】:

问题陈述:- 给定一个由 N 个正整数组成的向量和一个整数 X。任务是找到向量中 X 的频率。

Input:
N = 5
vector = {1, 1, 1, 1, 1}
X = 1
Output: 
5
Explanation: Frequency of 1 is 5.

Error:-
possibly your code does not work correctly for multiple test-cases (TCs).

The first test case where your code failed:

Test Cases Passed: 
1 /21
For Input: 
10017
10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10.................
 Input is too large Download Full File 
Your Code's output is: 
20480
It's Correct output is: 
10017
Output Difference
2048010017
int findFrequency(vector<int> v, int x){
    // Your code here
    
    int static count;
    for(auto it = v.begin();it!=v.end();it++)
    {
        if(*it == x)
        count++;
    }
    
    return count;
    
    
}

【问题讨论】:

  • int static count;为什么要在这里添加static?它可能没有用,并且是您的错误的来源。
  • count 很可能不是 static 并被初始化为 0
  • @MikeVine:大概是因为static 将其初始化为零,一次.
  • 你有问题吗?
  • 感谢您的评论。我删除了静态并重新运行它。为什么我知道它是一个错误。在这里使用 static 的原因是,在函数中使用时,与 auto 相比 value 应该是可用的。

标签: c++


【解决方案1】:

不要在你的函数中使用静态计数

这就是这里的问题,因为计数范围已增加到每个文件(在 C 中)或每个类(在 cpp 中)。

【讨论】:

  • 这段代码中没有类,count 的范围也没有改变。但它的生命周期现在延长到程序结束。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 2021-12-27
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
相关资源
最近更新 更多