[英]how to use data stored in a map to sort an array using std::sort() function in c++?
我想使用 hash map 根據 map 的值對字符串進行排序。但我找不到合適的方法。請幫我找到合適的方法所以這是我編寫的 c++ 代碼請幫助我如何更好地編寫它我想知道如何通過傳遞數據結構進行排序來使用 std::sort()
#include<bits/stdc++.h>
using namespace std;
unordered_map<char,int>m;
bool h(char a,char b)
{
return m[a]<=m[b];
}
int main()
{
int t;
cin>>t;
while(t--)
{
//unordered_map<char,int>m;
for(int i=1;i<=26;i++)
{
char a;
cin>>a;
m[a]=i;
}
string s;
cin>>s;
sort(s.begin(),s.end(),h);
cout<<s<<endl;
//m.erase(m.begin(),m.end());
//cout<<endl<<m.size();
}
}
您的比較function 不滿足嚴格的弱訂購要求。
return m[a] <= m[b];
應該是return m[a] < m[b];
通過該更改,您的程序可以正常工作並按照 map 的順序對std::string
進行排序。 如果您輸入字符zyxwvutsrqponmlkjihgfedcba
,您的sort
將按字母倒序對string
進行排序。
建議:
了解為什么不應該包含<bits/stdc++.h>
。 改為包含正確的標題:
#include <algorithm> #include <iostream> #include <string> #include <unordered_map>
盡量避免像26
這樣的幻數。 您可以像這樣制作循環以獲得相同的效果:
for(int i = 0; i <= 'Z'-'A'; i++)
1-26和0-25 (如上述循環產生的)將具有相同的效果。
避免使用諸如m
之類的全局變量。 您可以將其設為本地並在仿函數中引用它,例如 lambda。
我將假設那些被稱贊的台詞是你試圖開始工作的。
#include <unordered_map>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
cout << "enter number of times" << endl;
int t;
cin>>t;
while(t--)
{
unordered_map<char,int>m;
cout << "enter 26 characters" << endl;
for(int i=1;i<=26;i++)
{
char a;
cin>>a;
m[a]=i;
}
cout << "enter a string" << endl;
string s;
cin>>s;
sort(s.begin(),s.end(), [&](char a, char b)
{
return m[a]<m[b];
});
cout<<s<<endl;
m.erase(m.begin(),m.end());
cout<<endl<<m.size();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.