Group sorting a vector in C++

c++, std, vector, visual-c++

Solution

Using the STL, it's straightforward to insert your own comparison functions. You want to define a comparison function that compares on group first, and then compares on the other attributes.

static bool CompareWidget(const Widget& w1, const Widget& w2)
{
    if(w1.GetGroupNumber() != w2.GetGroupNumber())
        return (w1.GetGroupNumber() < w2.GetGroupNumber());
    if(w1.GetHeight() != w2.GetHeight())
        return (w1.GetHeight() < w2.GetHeight();
    /// etc
    return false;
}


 static void SortWidgetVector(WidgetVector& widgetVector)
 {
      std::sort(widgetVector.begin(), widgetVector.end(), CompareWidget);
 }

Problem

I have a std::vector full of objects, each with a numeric group identifier associated with them. The object also has properties such as "size" and "name". I need to be able to sort the vector of objects by name, size and other properties while keeping them grouped together (e.g. by the group identifier mentioned above). How can this goal be accomplished?

Original source