【发布时间】:2014-09-11 20:16:45
【问题描述】:
我正在尝试理解重载方法,尤其是关于 bool operator()。 请尝试理解。我确实尝试阅读一些关于重载运算符的文章,但仍然无法理解;/
我有来自 STL 的 set 容器,它会自动按字母顺序对其“对象”进行排序,但我想对其进行修改,以便它可以根据字符串的长度对字符串进行排序。
这是工作代码,我很难理解
#include <iostream>
#include <set>
#include <iterator>
using namespace std;
struct MyOrder
{
bool operator()(const string &first, const string &second)
{
int length1 = first.length(); //** assigning length of strings (arguments)
//** to int, so that we will compare their lengths
int length2 = second.length(); //** same story**//
if(length1 == length2) //** if both strings are the same length, code will return
//** true, but what does is mean first < second ?, will it
swap places of arguments or what ?
return (first < second);
return (length1 < length2); //** same story, if they are not the same length, than
//** what ? return true, and swap arguments' places ?
}
}
int main(void)
{
set<string, Myorder> names;
names.insert("Tony Soprano");
names.insert("Christopher Moltisanti");
set<string>::iterator it;
for(it = names.begin(); it != names.end(); ++it)
{
cout << *it << endl;
}
}
【问题讨论】:
-
operator()应该是const(虽然这不是必需的) -
Myorder与MyOrder不同 -
functionoid 应该是严格的弱排序,这意味着当且仅当第一个参数绝对位于第二个参数的“左侧”时,它才会返回 true。如果它们相等,那么第一个并不总是“在左边”,所以它应该返回 false。如果感到困惑,想想
operator<做了什么。 -
哪一部分你不明白?
Myorder::operator()是如何工作的,或者它是如何传递给std::set的? -
@Slava 我假设问题是
operator()函数内用 cmets 编写的问题