Home > database >  How to sort a string of name and age based on age using STL algorithms in. c
How to sort a string of name and age based on age using STL algorithms in. c

Time:10-28

I am trying to sort a vector of strings {"Josh 67", "Emily 42", "Rich 14", "Janet 1"} based on the age provided along with the names. I don't wanna use any loops and want to use STL Algorithms and lambda function to sort it.

auto SortString = [](string a, string b)
{
    return a > b;
};

vector<string> SortedByAge(vector<string> unsorted)
{
    sort(unsorted.begin(), unsorted.end(), SortString);
    return unsorted;
}



int main()
{
    vector<string> result = SortedByAge({"Josh 67", "Emily 42", "Rich 14", "Janet 1"});
    for(auto x : result)
    {
        cout << x << endl;
    }
}

This is the code I have so far, however, it does not seem to be working. I would appreciate any help.

CodePudding user response:

For example you can use a lambda expression with standard C function sscanf as for example

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <cstdio>

int main() 
{
    std::vector<std::string> v = 
    {
        "Josh 67", "Emily 42", "Rich 14", "Janet 1"
    };

    std::sort( std::begin( v ), std::end( v ),
        []( const auto &s1, const auto &s2 )
        {
            unsigned int n1;
            sscanf( s1.data(), "%*s%u", &n1 );
            unsigned int n2;
            sscanf( s2.data(), "%*s%u", &n2 );
            return n1 < n2;
        } );

    for ( const auto &s :v )
    {
        std::cout << s << '\n';
    }
}

The program output is

Janet 1
Rich 14
Emily 42
Josh 67

CodePudding user response:

user4581301 explained it perfectly. I'm suggesting an implementation here to sort in a descending order. Please pay attention that I changed Josh's age from 67 to 7 to test my code.

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

    using namespace std;

    auto SortString = [](string a, string b)
    {
        stringstream s1(a);
        stringstream s2(b);
        string age1Str;
        string age2Str;

        for (int count = 0; count<2; count  ) {
            getline(s1, age1Str, ' ');
            getline(s2, age2Str, ' ');
        } 

        int age1 = stoi(age1Str);
        int age2 = stoi(age2Str);

        return age1 > age2;

    };

    vector<string> SortedByAge(vector<string> unsorted) { 
    sort(unsorted.begin(), unsorted.end(), SortString);
    return unsorted;
    } 



    int main() {
        vector<string> result = SortedByAge({"Josh 7", "Emily 42", "Rich 14", "Janet 1"});
        for(auto x : result) {
            cout << x << endl;
        }
     }
  • Related