如何更改配对(>和<)运算符行为?
How to change pair (> and <) operators behavior?
我正在尝试对vector< pair<int,char> >
进行排序,但我想更改对类型的比较运算符的行为,这样,如果第一个值相等,并且它与(>)运算符进行比较,我希望它将第二个值与(<)运算符进行比较。
我尝试这样做是为了解决uva上的"什么是密码分析?"问题。这是我的方法:
string toLower(string in){
string out;
for(int i=0;i<in.length();i++){
if(in.at(i)<='Z' && in.at(i)>='A'){
out+=in.at(i)+('a'-'A');
}
else if(in.at(i)<='z' && in.at(i)>='a'){
out+=in.at(i);
}
}
return out;
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("tmp.txt","w",stdout);
vector< pair<int,char> >vp;
pair<int,char> tp;
for(char a='a';a<='z';a++){//buliding a table of values and chars
tp= make_pair(0,a);
vp.push_back(tp);
}
int T;
cin >> T;
string s;
cin.ignore();
for(int i=0;i<T;i++){
getline(cin,s);
s=toLower(s);//remove special chars and convert all to lower
int l=s.length();
for(int j=0;j<l;j++){
vp[s[j]-'a'].first+=1;//increasing the value of each char found
}
}
sort(vp.begin(),vp.end());//ascending sort
for(int j=25;j>=0;j--){
cout << (char)(vp[j].second -('a'-'A')) << " " <<vp[j].first << endl;//cout the Capital char and its value backwards (Descending)
}
//system("pause");
return 0;
}
但这就是输出的样子:
S 7
T 6
I 5
E 4
O 3
W 2
U 2
N 2
H 2
A 2
Y 1
Q 1
M 1
C 1
Z 0
X 0
V 0
R 0
P 0
L 0
K 0
J 0
G 0
F 0
D 0
B 0
例如,我希望W U N H A
是A H N U W
我在其他问题中读过关于重载的文章,但我不知道在这里实现它
这是通过向sort
传递自定义比较器函数来完成的。你可以用这样的lambda最容易地做到这一点:
sort(
vp.begin(),
vp.end(),
[](const pair<int,char>& lhs, const pair<int,char>& rhs) -> bool {
return lhs.first != rhs.first
? lhs.first < rhs.first
: lhs.second < rhs.second;
}
);
这段代码先按升序first
排序,然后按升序second
排序,但您可以调整两个比较的优先级和方向,以按您想要的方式排序。
只需提供自己的比较功能:
bool comp(const std::pair<int, char>& a, const std::pair<int, char>& b)
{
if (a.first > b.first) {
return true;
} else if (a.first == b.first && a.second < b.second) {
return true;
}
return false;
}
然后在排序时使用它:
sort(vp.begin(),vp.end(), comp);
我正在尝试对向量<pair>但我想更改比较的行为
只需定义一个合适的二进制谓词函数,并将其作为第三个参数传递给std::sort
。请记住,它应该实现严格的弱排序:
bool foo(const pair<int,char>& lhs, const pair<int,char>& rhs)
{
// implement logic here
}
....
sort(vp.begin(),vp.end(), foo);
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 如何为运算符<<
- Qt过载数据流运算符<<
- 我可以使用define调用运算符<<
- 运算符<<(ostream&os,..)用于模板类
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多
- Can运算符<<用于设计我们自己的输出显示方式