mercredi 7 avril 2021

Sort the numbers in an array while leaving the letters in their original positions?

I am learning the std::sort function and wonder if I could use it to sort an array mixing with digits and letters. Here is the non-working code.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>                                                                                                                                                                                      

using namespace std;                                                                                                                                                                                      

bool is_digit(const string& s)
{
    return '0' <= s[0] && s[0] <= '9';
}                                                                                                                                                                                                         

struct compare_lt
{                                                                                                        
    inline bool operator() (const string& s1, const string& s2)
    {
        if (is_digit(s1) && is_digit(s2))
            return s1.compare(s2) < 0;
        return true;                                                                                     
    }
};

int main()
{
    vector<string> s = {"9", "6", "a", "c", "d", "1", "2", "5", "3", "f", "e", "4" };                    
    sort(s.begin(), s.end(), compare_lt());
    for (auto& i: s)                                                                                         
        cout << i << " ";
    cout << endl;
}

I expect the output like below, only sort numbers but leave letters in their original positions. I am aiming to only use one sort operation.

1 2 a c d 3 4 5 6 f e 9

I don't know how to get comparator function correct.

Aucun commentaire:

Enregistrer un commentaire