【发布时间】:2014-11-07 15:14:09
【问题描述】:
我试图了解 STL 类模板中使用的运算符重载,例如:映射或对。
让我给你介绍一下我的代码:
#include <iostream>
#include <iomanip> // left, setw
#include <string>
#include <map>
#include <utility> // pair
#include <algorithm> // count if
using namespace std;
typedef pair <string, int> Emp;
typedef map <string, Emp> MAP;
class Zakr{
int min, max;
public:
Zakr(int min, int max): min(min), max(max){}
bool operator()(const pair<const string, Emp> &p) const{
int wage = p.second.second;
return (min < wage) && (wage < max);
}
};
void print (const MAP& m) {
MAP::const_iterator it, fin = m.end();
for(it = m.begin(); it != fin; it++)
cout << "Key: " << left << setw(7) << it -> first
<< "Name: " << setw(10) << it->second.first
<< "Wage: " << it->second.second << endl;
}
int main(void){
MAP emp;
MAP object;
emp["John"] = Emp("John K.", 1900);
emp["Tania"] = Emp("Tania L.", 1900);
emp["Jeremy"] = Emp("Jeremy C", 2100);
emp["Susie"] = Emp("Susie W.", 3100);
emp["Toto"] = Emp("Toto T.", 9900);
emp["Adrian"] = Emp("Adrian N.", 1600);
emp["Germy"] = Emp("Germy P.", 2600);
print(emp);
int mn = 0, mx = 2000;
int how_much = count_if(emp.begin(), emp.end(), Zakr(mn, mx));
cout << how_much << " earn from"
<< mn << " to " << mx << endl;
}
我正在努力理解一些位,尤其是其中一个,即:
class Zakr{
int min, max;
public:
Zakr(int min, int max): min(min), max(max){}
bool operator()(const pair<const string, Emp> &p) const{
int wage = p.second.second;
return (min < wage) && (wage < max);
}
};
所以我构建了一个名为 Zakr 的类,这样我就可以使用它来确定 count_if 语句中的函子。
我说的对吗?
我初始化私有字段 min 和 max 以在构造函数中使用它们,然后重载的运算符可以根据它们自己的值返回布尔值。 最困难的部分是理解布尔运算符重载。
bool operator()(const pair<const string, Emp> &p) const{
int wage = p.second.second;
为什么我需要 1* 制作一对无用的字符串值和 EMP?
由于我感兴趣的所有内容都存储在 EMP 中,即:将用于重载的 int 值存储在 Emp 中。
为什么我不能像这样访问存储在 Emp 中的 int:
bool operator(Emp &p)
{
int wage = p.second;
return (min < wage) && (wage < max);
}
为什么我需要像这样制作另一对:(const pair &p),如果我感兴趣的只是存储在名为 Emp 的对中的值。
为什么我需要用上面命名对的无用第一个元素制作另一对:字符串。 我不会用它,那为什么要编译代码呢?
我确实尽力尽可能清楚地解释我的疑问。 希望有人能理解这篇相当长的帖子。
干杯!
【问题讨论】: