具有不满足严格弱排序的值的 C++ 顺序范围

c++ order range with values that doesn't fulfill strict weak ordering

本文关键字:C++ 顺序 范围 排序 不满足      更新时间:2023-10-16

我需要对范围内的值进行排序,以便该范围表示一个链

struct Link
{
int id;
int next;
};

Link::idLink::next的值是任意的,并且它们本身不提供任何语义含义(无论如何都不用于排序算法(。

两个链接(排序后(之间的关系为:lhs.next正好rhs.id

前提 条件

  • 无序range保证保存可以精确排序到一个中的值。
  • 保证值集中没有递归(无循环(

例:

std::vector< Link> range{ { 4, 1}, { 1, 5}, { 3, 4}, { 2, 3}};
auto chain = some_algorithm( range);
// expect the ordering to be: { { 2, 3}, { 3, 4}, { 4, 1}, { 1, 5}};

我至少可以想到两种方法,但我怀疑这已经以一种惯用的方式解决了。所以,我的问题是:如何以惯用的方式解决这个问题?

我怀疑是否有惯用的方法,因为这不是常见的情况。

链接主要由指针/迭代器完成(例如std::list(,实际的链接大多是在插入时完成的。

有趣的是找到第一个链接以及如何处理循环链接和错误情况。

这是我想到的:

"概念"R是某种行为类似于范围的类型,可能是容器,也可能是其他东西。

如果range有缺口(链接方面(,将订购新的链。我不想有一些"断言输出"或抛出。我仍然保持我的目标,因为在我的用例中,我知道所有值都可以形成一个链。

template< typename R, typename ISP>
R chain( R range, ISP is_link_predicate)
{
auto first = std::begin( range);
auto current = first;
const auto last = std::end( range);
while( current != last)
{
const auto next = current + 1;
// try to find a value in [next, last) that can be linked with *current.
auto link = std::find_if( next, last, [current,is_link_predicate]( auto& value){
return is_link_predicate( *current, value);
});
if( link != last)
{
using std::swap;
swap( *next, *link);
current = next;
}
else
{
// we need to check if some value in [next, last) can be "inserted" in the
// beginning of the chain. That is, can form a link with *first.
auto new_first = std::find_if( next, last, [first,is_link_predicate]( auto& value){
return is_link_predicate( value, *first);
});
if( new_first != last)
{
// we got a new_first, we need to rotate it first
//
// C = current
// N = next (not ordered).
// - = ordered values
// = = not ordered values
// X = value to be "inserted" first, new_first
//
// -----CN====X===  we start with
// X-----C========  we end up with
//
std::rotate( first, new_first, new_first + 1);
current = next;
}
else
{
// no values in [next, last) is part of the current chain.
// we start building the next chain.
current = next;
first = current;
}
}
}
return range;
}

评论?

首先,你正在做的不是排序,所以要考虑排序。你永远无法判断A是在B之前还是之后,你可以只知道AB之前是正好是1还是之后正好是1。所以排序在这里不能帮助你,甚至拓扑排序也没有。

一种算法:对于链A1..An回溯所有可以与之链接的元素X,例如A1..AnXXA1..An,然后对新链重复此操作。起始链是空链,任何元素都可以与之链接。