简体   繁体   中英

how to use data stored in a map to sort an array using std::sort() function in c++?

i wanted to use a hash map to sort a string on the basis of the values the map has.but i just could not find a suitable way..please help me find a way.so here is a c++ code that I wrote please help me how to write it better i want to know how to use std::sort() by passing a data structure for sorting

#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();
    }
}

Your Compare function does not fulfill the strict weak ordering requirement.

return m[a] <= m[b]; should be return m[a] < m[b];

With that change, your program works correctly and sorts the std::string in the order your map holds. If you enter the characters zyxwvutsrqponmlkjihgfedcba your sort will sort the string in reverse alphabetical order.

Suggestions:

  • Read about why you shouldn't include <bits/stdc++.h> . Include the correct headers instead:

     #include <algorithm> #include <iostream> #include <string> #include <unordered_map>
  • Try to avoid magic numbers like 26 . You can make your loop like this for the same effect:

     for(int i = 0; i <= 'Z'-'A'; i++)

    1-26 and 0-25 (as the above loop produces) will have the same effect.

  • Avoid global variables such as m . You can make it local and refer to it in a functor , like a lambda.

  • Read Why is using namespace std; considered bad practice?

I'm going to assume that the commended out lines were what you were trying to get working.

#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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM