预备知识
- set 容器
本题中可能需要使用的 set 方法:
|
成员方法 |
功能 |
|
begin() |
返回指向容器中第一个(注意,是已排好序的第一个)键值对的双向迭代器。如果 map 容器用 const 限定,则该方法返回的是 const 类型的双向迭代器。 |
|
end() |
返回指向容器最后一个元素(注意,是已排好序的最后一个)所在位置后一个位置的双向迭代器,通常和 begin() 结合使用。如果 map 容器用 const 限定,则该方法返回的是 const 类型的双向迭代器。 |
|
find(key) |
在 map 容器中查找键为 key 的键值对,如果成功找到,则返回指向该键值对的双向迭代器;反之,则返回和 end() 方法一样的迭代器。另外,如果 map 容器用 const 限定,则该方法返回的是 const 类型的双向迭代器。 |
|
empty() |
若容器为空,则返回 true;否则 false。 |
|
size() |
返回当前 map 容器中存有键值对的个数。 |
|
insert() |
向 map 容器中插入键值对。 |
- set 自定义元素排序
class MyCompare{
bool operator()(int v1,int v2){
return v1 > v2;
}
};
int main() {
set<int, MyCompare> s;
// ...
return 0;
}
- 遍历算法
/*
遍历算法 遍历容器元素
@param beg 开始迭代器
@param end 结束迭代器
@param _callback 函数对象
*/
for_each(iterator beg, iterator end, _callback);
思路、步骤
- 设计员工类(Employee)
- 成员变量:姓名(string name),工资(int salary)
- 成员方法:构造方法、公共的访问方法
- 创建 set 容器对象,set<Employee,myCompare> s; 第一个模板参数指定容器中的元素类型 Employee,第二个参数为自定义排序规则,这里采用仿函数实现,该仿函数按照工资由高到底的顺序排序:
class myCompare {
public:
bool operator()(const Employee& e1, const Employee& e2) const {
return e1.getSalary() > e2.getSalary();
}
};
- 按照要求创建 3 个 Employee 对象
- 使用 set 的 insert() 方法添加元素
- 使用 for_each(iterator beg, iterator end, _callback); 对 set 容器对象进行遍历,遍历的过程中根据规则计算出应纳税额并输出。
代码实现
#include <iostream>
#include <set>
#include <algorithm>
#include <iomanip>
using namespace std;
class Employee {
private:
string name;
int salary;
public:
Employee(string name, int salary) {
this->name = name;
this->salary = salary;
}
string getName() {
return name;
}
void setName(string name) {
this->name = name;
}
int getSalary() const {
return salary;
}
void setSalary(int salary) {
this->salary = salary;
}
};
class myCompare {
public:
bool operator()(const Employee& e1, const Employee& e2) const {
return e1.getSalary() > e2.getSalary();
}
};
int main() {
set<Employee,myCompare> s;
Employee e1("张三", 6500);
Employee e2("李四", 8000);
Employee e3("王五", 100000);
s.insert(e1);
s.insert(e2);
s.insert(e3);
for_each(s.begin(), s.end(), [](Employee e) {
double tax = 0.0;
double taxIncome = e.getSalary() - 3500;
if (taxIncome <= 0) {
tax = 0.0;
}
else if (taxIncome <= 1500) {
tax = taxIncome * 0.03;
}
else if (taxIncome <= 4500) {
tax = taxIncome * 0.10 - 105;
}
else if (taxIncome <= 9000) {
tax = taxIncome * 0.20 - 555;
}
else if (taxIncome <= 35000) {
tax = taxIncome * 0.25 - 1005;
}
else if (taxIncome <= 55000) {
tax = taxIncome * 0.30 - 2755;
}
else if (taxIncome <= 80000) {
tax = taxIncome * 0.35 - 5505;
}
else {
tax = taxIncome * 0.45 - 13505;
}
cout<<fixed<<setprecision(1);
cout << e.getName() << "应该缴纳的个人所得税是:" << tax << endl;
});
return 0;
}



京公网安备 11010502036488号