操作员过载'operator()'
Operator Overloading 'operator()'
我正在实现Dijkstra的算法,我想使用STL的'priority_queue'来加快编码过程,但是就像我尝试用C++编码一样,我对语言的缺乏理解正在减慢我的速度。我在 http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/找到了这个例子,但不明白以下内容在做什么:
// constructing priority queues
#include <iostream>
#include <queue>
using namespace std;
class mycomparison
{
bool reverse;
public:
mycomparison(const bool& revparam=false)
{reverse=revparam;}
bool operator() (const int& lhs, const int&rhs) const
{
if (reverse) return (lhs>rhs);
else return (lhs<rhs);
}
};
int main ()
{
int myints[]= {10,60,50,20};
priority_queue<int> first;
priority_queue<int> second (myints,myints+4);
priority_queue< int, vector<int>, greater<int> > third (myints,myints+4);
// using mycomparison:
priority_queue< int, vector<int>, mycomparison > fourth;
typedef priority_queue<int,vector<int>,mycomparison> mypq_type;
mypq_type fifth (mycomparison());
mypq_type sixth (mycomparison(true));
return 0;
}
更具体地说,"bool operator()(const int&lhs, const int&rhs) const"是让我绊倒的原因。其余的我很好。我认为它重载了运算符,但"operator()"对我来说毫无意义。任何帮助将不胜感激。
本质上,operator()
"只是"另一个可以重载的运算符,因此您所知道的有关运算符重载的所有内容仍然适用 - 它很有用,因为它可以应用于具有与调用函数相同的语法的对象,例如
MyClass f;
f(); // i.e. f.operator()();
也就是说,除此之外,关于函子等还有很多话可以说 - 你可能想在谷歌上搜索函子/函数对象以获取更多信息。这是一个链接:
http://en.wikipedia.org/wiki/Function_object
在上面的代码中,priority_queue
采用一个比较函子,它用来对你放入队列的内容进行排序。第一个队列(fifth
)使用正常排序;第二个队列(sixth
)使用反向排序。
这是函数调用运算符,你可以像这样使用它:
mycomparison mycomp; //defines an object
mycomp(1,2); // invokes operator()(int,int)
bool operator () ( const int &, const int & );
这是一个函数,operator()
的重载,它接受两个整数并返回一个布尔值。 const
表示无法更改该值。它代表常量。
相关文章:
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 'operator='已弃用:改用 QDir::setPath()
- <<操作员在下面的行中工作
- 过载'operator new'如何导致无限循环?
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 处理"no operator found"
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 运算符重载:"operator+"必须采用零个或一个参数
- 使用 operator() 扩展 Eigen::EigenBase
- 比根<操作员
- 错误消息:使用"string* +="后"no match for 'operator+='"
- SFINAE不能防止模棱两可的操作员过载吗?
- 为什么逗号运算符在运算符[]中打电话给操作员[],而不是在Operator()内部调用
- 操作员过载'operator()'
- STL 减少操作员和"invalid operator<"误差