Acton Dev

Sharing projects and stuff

Category Archives: C++

Qt C++ : order a QList of objects depending on the value returned of an object function

//
template <class Type, typename Func>
static QList<Type> orderList(QList<Type> list, Func func, bool ascending = true ){
    int count = list.count();
    
//buble sorting
    for(int i=count-2; i>=0; i--){
        for(int j=0; j<=i; j++){
            if(ascending){
                if( func(list.at(j)) > func(list.at(j+1)) && ascending ){
                    Type temp = list.at(j);
                    list.replace(j, list.at(j+1));
                    list.replace(j+1, temp);
                }
            }
            else if( func(list.at(j)) < func(list.at(j+1)) ){
                Type temp = list.at(j);
                list.replace(j, list.at(j+1));
                list.replace(j+1, temp);
            }
        }
    }
    return list;
}

//

and usage (inside tools.h i have my helper functions):

//
m_list = Tools::orderList(m_forwardsRelatedList, std::mem_fun(&Node::angleOffset));
//

Where m_list is a QList<Node*> and Node::angleOffset() (non static, public member function of class Node) returns a number.
So i now can sort the list, having the Node* objects sorted depending on the value returned by angleOffset() function !

Advertisements