我想 std::partial_sort_copy()
一个数组,但使用自定义比较器函数。问题是,此函数同时使用了要比较阵列单元格的 value 。
为了讨论,假设我的comaprison函数就像
template <typename T>
bool myCompare(size_t lhs_index, const T& lhs, size_t rhs_index, const T& rhs) {
T lhs_compound = lhs * (lhs_index % 2 ? -1 : 1);
T rhs_compound = rhs * (lhs_index % 2 ? -1 : 1);
return (lhs_compound <= rhs_compound);
}
(如果您喜欢... 起初,我想到了使用 我应该做什么?pair<size_t, T>
S的比较对象 - 但这不起作用,因为这意味着我的输出将是这样的成对的数组,我不想要。实际上,我需要不实现任何东西 - 所以没有对的阵列,索引或任何此类东西。
类似的东西可能会有所帮助。
它创建一个索引数组,然后根据比较器(间接到初始数组)对此数组进行排序:
template <typename IT, typename Comp>
struct MyCmp
{
explicit Cmp(const IT it, Comp& comp) : it(it), comp(comp) {}
bool operator (std::size_t lhs, std::size_t rhs) const
{
return comp(lhs, *(it + lhs), rhs, *(it + rhs));
}
const IT it;
Comp comp;
};
template<typename IT, typename IT2, typename Comp>
void mypartialsort(IT begin, IT end, IT2 dbegin, IT2 dend, Comp comp)
{
std::vector<size_t> indexes;
for (size_t i = 0, size = end - begin; i != size; ++i) {
indexes.push_back(i);
}
MyCmp<IT, Comp> mycomp(begin, comp);
const std::size_t min_size = std::min(end - begin, dend - dbegin);
std::partial_sort(v.begin(), v.begin() + d, v.end(), mycomp);
for (std::size_t i = 0; i != min_size; ++i, ++dbegin) {
*dbegin = *(begin + v[i]);
}
}