简体   繁体   中英

Is there an easy way to sort a CObList?

I am pretty new to MFC and C++ applications, so I apologize if my question is too trivial. Anyway my boss has some legacy code written in VC++ and there is a list of objects stored in a CObList that I need to sort. I need to sort this list based on some integer value stored in that object. Is there an easy way to do this?

You probably know this already: if you are new to C++, please don't use the MFC collection classes ( CObList , CArray etc.). Instead, use the STL ( std::vector , std::list etc.). The Product Manager for Visual C++ said as much here (look for the post by RonaldLaeremans).

But sometimes you have legacy code and you have to use the MFC collections.


Do you really need to sort the list, or can you live with a sorted copy of the list? If the latter, it would be pretty easy to copy the list into a std::vector and sort that. Of course you would only copy pointers or references, so you do not incur the overhead of creating additional copies of the objects stored in the list.

Something like this:

std::vector<const CObject*> v;
for (POSITION pos = theList.GetHeadPosition(); pos != NULL;) {
    v.push_back(theList.GetNext(pos));
}

// Use your own comparison function. Here I used a lambda (available
// in Visual C++ 2010), but you could pass any function that returns
// true iff the first item is less than the second item.
auto comparisonFunction = [](const CObject* left, const CObject* right)->bool {
    return (left->m_yourStoredValue < right->m_yourStoredValue);
};

std::sort(v.begin(), v.end(), comparisonFunction);

// Use the results...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM