sorting a vector of structs

calccrypto picture calccrypto · Feb 3, 2011 · Viewed 114.1k times · Source

I have a vector<data> info where data is defined as:

struct data{
    string word;
    int number;
};

I need to sort info by the length of the word strings. Is there a quick and simple way to do it?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Feb 3, 2011

Use a comparison function:

bool compareByLength(const data &a, const data &b)
{
    return a.word.size() < b.word.size();
}

and then use std::sort in the header #include <algorithm>:

std::sort(info.begin(), info.end(), compareByLength);