简体   繁体   English

C++中如何很好的实现泛型排序

[英]How to nicely implement generic sorting in C++

I'm trying to brush up on my C++ templating, and I'm running into the following issue.我正在尝试重温我的 C++ 模板,但遇到了以下问题。 I'm implementing some basic in-place sorting methods, which I want to work for various types of data containers that can be indexed, and the elements of which can be compared.我正在实现一些基本的就地排序方法,我希望这些方法适用于可以索引的各种类型的数据容器,并且可以比较其中的元素。 Specifically, the methods should work for both plain arrays, std::array , std::vector , etc. For some methods this is rather straightforward, like insertion sort:具体来说,这些方法应该适用于普通 arrays、 std::arraystd::vector等。对于某些方法,这相当简单,例如插入排序:

template<typename T>
void insertion_sort(T& data)
{
    if (std::size(data) < 2)
        return;

    for (int j = 1; j < std::size(data); ++j)
    {
        int i = j;
        while (i > 0 && data[i - 1] > data[i])
        {
            swap_index(data, i, i - 1); // basic helper that swaps data at two indices
            --i;
        }
    }
}

However, for some methods, I also need to know the actual type of the elements stored in data .但是,对于某些方法,我还需要知道存储在data中的元素的实际类型。 An example is merge sort: I need to allocate some scratch space to be used for copying stuff around.一个例子是合并排序:我需要分配一些临时空间用于复制周围的东西。 I tried something like this:我试过这样的事情:

template<typename T>
void mergesort(T& data)
{
    typedef decltype(*std::begin(data)) inner_type;
    inner_type* scratch = new inner_type[std::size(data)];
    ...

but that just gives me errors like "error C2528: 'scratch': pointer to reference is illegal".但这只会给我错误,例如“错误 C2528:'scratch':指向引用的指针是非法的”。

In C# I'd just use something like where T: IComparable<T> , and have a parameter of type IList<T> , which seems to be closer to what I want to achieve: have a type T that is comparable, and as parameter some indexable collection of Ts.在 C# 中,我只使用类似where T: IComparable<T>的东西,并且有一个IList<T>类型的参数,这似乎更接近我想要实现的目标:有一个可比较的类型 T,并且作为参数一些可索引的 Ts 集合。 What is the "proper" way to achieve this with C++ templates?使用 C++ 模板实现此目的的“正确”方法是什么? Or should I use something other than templates here?或者我应该在这里使用模板以外的东西吗? I want to sort the container in place, so I don't think I want to use something like iterators.我想就地对容器进行排序,所以我不认为我想使用迭代器之类的东西。

The clue is in the error message inner_type is a reference not the value type you are looking for.线索在错误消息中inner_type is a reference not the value type you are looking for. The following works for me (C++14 is required).以下对我有用(需要 C++14)。

#include <type_traits>

typedef std::remove_reference_t<decltype(*std::begin(data))> inner_type;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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