Ali*_*sam 0 c++ operator-overloading std-pair
我正在尝试排序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;
}
Run Code Online (Sandbox Code Playgroud)
但这是输出的样子:
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
Run Code Online (Sandbox Code Playgroud)
所以例如我想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;
}
);
Run Code Online (Sandbox Code Playgroud)
此代码按升序排序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;
}
Run Code Online (Sandbox Code Playgroud)
然后在排序时使用它:
sort(vp.begin(),vp.end(), comp);
Run Code Online (Sandbox Code Playgroud)