【问题标题】:How is it possible to count, how many elements in an array satisfy certain conditions (C++)?如何计算数组中有多少元素满足特定条件(C++)?
【发布时间】:2026-01-05 03:45:01
【问题描述】:

我是 C++ 初学者,我需要一个基本问题的帮助。我有一个数据集(数组),任务是计算有多少元素满足给定条件。

公司存储其员工的年龄和薪水。我们需要编写一个程序,告诉你 L 岁以上有多少人的薪水低于 M。

输入

标准输入第一行工人数(0≤N≤100),年龄限制(1≤L≤100) 工资限制(1≤M≤2,000,000)及以下为每行一人年龄 (1≤K≤100)和工资(1≤F≤2,000,000)。

输出

单行标准输出中,年龄在L以上,工资低于M的人 必须写下工人的数量。

#include <iostream>
using namespace std;
int main()
{
    int N;
    int K;
    int L;
    int F;
    int M;
    cin >> N >> K >> L >> F >> M;
    int arr[N];
    for (int i=0; i<N; ++i)
    {
        cin >> arr[i];
    }
    int DB=0;
    for (int i=0; i<N; ++i)
 {
                 for (int DB; K>L && F<M; DB=DB+1)
                    {


                    }
    }
    cout << DB << endl;
    return 0;
}

我尝试使用 for 循环来解决问题。很明显,代码中存在基本错误。你能帮我解决问题吗?上面的代码是好方法还是有更好的解决方案?

提前感谢您的帮助。

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow!您能否澄清输入,或提供一个示例输入?
  • 当您不知道如何继续时,将问题分解为多个步骤通常是个好主意。例如,你能数出数组中元素的数量吗?不,不是N 的简单回答。我的意思是你的循环设置。统计元素个数,添加评论\\ TO DO: I need to check a condition before counting this element.
  • C++ 标准库在标题&lt;algorithm&gt; 中包含count_if() 算法,该算法计算范围内满足所提供条件的元素数。

标签: c++ arrays for-loop variables counting


【解决方案1】:

这当然是解决问题的一种创造性方法! 解决这个问题的更直接的方法是检查每个元素,并检查它是否匹配,如下所示:

#include <iostream>
using namespace std;
int main(){
  int numWorkers, ageLimit, salaryLimit, matchCount=0;
  cin >> numWorkers >> ageLimit >> salaryLimit;
  for (int i = 0; i < numWorkers; i++){
    int age, salary;
    cin >> age >> salary;
    if (age > ageLimit && salary < salaryLimit){
      matchCount++;
    }
  }
  cout << matchCount << endl;
  return 0;
}

【讨论】:

    【解决方案2】:

    这是一种方法,请注意,这只是基于您帖子的 cmets 的示例。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    // you need a way to capture the information of age and salary
    
    class Employee
    {
    public:
      Employee(int age, int salary) : m_age(age), m_salary(salary) 
      {}
      int Salary() const { return m_salary; }
      int Age() const { return m_age; }
    private:
      int m_age{0};
      int m_salary{0}; 
    };
    
    
    int main()
    {
      // an array of the employees with age and salary, avoid using native arrays
      std::vector<Employee> employees{{21,10000},{22,12000},
                                      {54,54500},{62,60000}, 
                                      {32,32000}};
      // some salary limit or use cin to read in it
      auto salaryLimit = 33000;
    
      // use count_if to count the number of employees under salary limit
      auto nrOfEmployees = std::count_if(employees.begin(), employees.end(), 
                           [=](const Employee& e){return e.Salary() < salaryLimit;});
      std::cout << nrOfEmployees << std::endl;
    
      return 0;
    }
    

    如果你想试试代码

    https://onlinegdb.com/Sy-qCXN8v

    【讨论】:

      最近更新 更多