假设您想partial_sort
在清单上做一个。您可以通过提供可以使用迭代器进行排序的比较函数将迭代器存储到集合中的列表中,如下所示:
struct iterator_less
{
bool operator() (std::list<int>::iterator lhs,
std::list<int>::iterator rhs) const
{
return (*lhs < *rhs);
}
};
typedef std::multiset<
std::list<int>::iterator, iterator_less
> iterator_set;
您可以让 set 执行排序,但由于它包含要列出的迭代器,您可以 list::splice 将它们拼接成一个 partial_sorted 列表:
std::list<int> unsorted, partialSorted;
unsorted.push_back(11);
unsorted.push_back(2);
unsorted.push_back(2);
unsorted.push_back(99);
unsorted.push_back(2);
unsorted.push_back(4);
unsorted.push_back(5);
unsorted.push_back(7);
unsorted.push_back(34);
// First copy the iterators into the set
iterator_set itSet;
for( auto it = unsorted.begin(); it!=unsorted.end();++it)
{
itSet.insert(it);
}
// now if you want a partial_sort with the first 3 elements, iterate through the
// set grabbing the first item in the set and then removing it.
int count = 3;
while(count--)
{
iterator_set::iterator setTop = itSet.begin();
partialSorted.splice(
partialSorted.begin(),
unsorted,
*setTop);
itSet.erase(setTop);
}
partialSorted.splice(
partialSorted.end(),
unsorted,
unsorted.begin(),
unsorted.end());