gpt4 book ai didi

c++ - 有没有一种简单的方法来对 CObList 进行排序?

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:21 25 4
gpt4 key购买 nike

我是 MFC 和 C++ 应用程序的新手,如果我的问题太琐碎,我深表歉意。无论如何,我的老板有一些用 VC++ 编写的遗留代码,并且有一个对象列表存储在我需要排序的 CObList 中。我需要根据存储在该对象中的某个整数值对该列表进行排序。有没有简单的方法可以做到这一点?

最佳答案

您可能已经知道这一点:如果您是 C++ 新手,请不要使用 MFC 集合类(CObListCArray 等)。相反,请使用 STL(std::vectorstd::list 等)。 Visual C++ 的产品经理说了这么多here (查找 RonaldLaeremans 的帖子)。

但有时您有遗留代码并且必须使用 MFC 集合。


真的需要对列表进行排序,还是您可以接受列表的排序拷贝?如果是后者,则很容易将列表复制到 std::vector 中并对其进行排序。当然,您只会复制指针或引用,因此不会产生为存储在列表中的对象创建额外拷贝的开销。

像这样:

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...

关于c++ - 有没有一种简单的方法来对 CObList 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4382844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com