[英]How is it possible to count, how many elements in an array satisfy certain conditions (C++)?
我是 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 循环解决问题。 很明显,代码中存在基本错误。 你能帮我解决问题吗? 上面的代码是一个好方法还是有更好的解决方案?
提前感谢您的帮助。
这当然是解决问题的创造性方法! 解决这个问题的更直接的方法是检查每个元素,并检查它是否匹配,如下所示:
#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;
}
这是一种方法,请注意,这只是基于对您帖子的评论的示例。
#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;
}
如果你想尝试代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.