正确的方法来测试容器是否实现.at()成员访问/ std :: sort兼容

Rus*_*Kax 7 c++ containers templates stl c++11

我正在寻找最佳/正确的方法来确定容器是否实现随机元素访问.at().在不同(stl)容器相对于彼此进行排序的情况下(比如对容器进行排序std::vector<int>,相对于std::vector<double>),我做了以下事情:

std::sort(toOrder.begin(), toOrder.end(), [&orderBy](int i, int j) -> bool {
    return orderBy.at(i) > orderBy.at(j);
});
Run Code Online (Sandbox Code Playgroud)

哪里

std::vector<int> toOrder;
std::vector<double> orderBy
Run Code Online (Sandbox Code Playgroud)

我可以将它包装在模板函数中,但我不确定限制或测试具有随机访问迭代器/ .at()的容器的最佳方法(当它们没有时,需要做一些昂贵的事情).

我有这个

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_set>

template <typename T, typename U>
void sorty(T& a, U const x) {
    std::sort(a.begin(), a.end(),
              [&x](int i, int j) -> bool { return x.at(i) > x.at(j); });
}

int main() {

    std::vector<int> toOrder(10);
    std::iota(toOrder.begin(), toOrder.end(), 0);
    std::vector<double> orderBy{0.2, 9.8,  4.0,  0.01,  15.1,
                                3.3, 9.01, 9.11, 100.1, 2.03};

    std::unordered_set<double> orderBy_s(orderBy.begin(),
                                         orderBy.end()); // no .at()

    sorty(toOrder, orderBy);

    for (auto i : toOrder) {
        std::cout << i << "\t";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

演示代码在这里

更新:我匆匆发布,没有编辑标题.我关注任何容器类型,而不仅仅是STL.我的例子使用了STL容器以方便和重现.

Pio*_*cki 11

基本上,这不是应该实现通用算法的正确方法.通常,人们会使用iteratorsstd::iterator_traits确定基础类型和允许的操作.如果要根据容器提供的接口(随机访问,非随机访问)执行不同的算法(具有不同的复杂性),则应执行以下操作.

首先,您的通用算法应该在范围而不是容器上运行.也就是说,这应该看起来像任何<algorithm>功能:

template <typename Iterator>
void sorty(Iterator first, Iterator last);
Run Code Online (Sandbox Code Playgroud)

其次,您应该编写应用不同排序方法的辅助函数,以尽可能多地利用容器的接口,从而以最有效的方式工作:

// O(N*lgN) complexity sorting
template <typename Iterator>
void sorty_helper(Iterator first, Iterator last,
                  std::random_access_iterator_tag);

// O(N*N) complexity sorting
template <typename Iterator>
void sorty_helper(Iterator first, Iterator last,
                  std::forward_iterator_tag);
Run Code Online (Sandbox Code Playgroud)

现在,您的原始sorty函数实际上应该只根据通过std::iterator_traits以下方式获得的迭代器的类型将迭代器转发到适当的辅助函数:

template <typename Iterator>
void sorty(Iterator first, Iterator last)
{
    sorty_helper(first, last,
                 typename std::iterator_traits<Iterator>::iterator_category());
}
Run Code Online (Sandbox Code Playgroud)

演示1

另一种方法是使用SFINAE技术启用/禁用功能模板:

#include <iterator>
#include <type_traits>    

template <typename Iterator>
typename std::enable_if<
    std::is_same<typename std::iterator_traits<Iterator>::iterator_category, std::random_access_iterator_tag>::value
    >::type
    sorty(Iterator first, Iterator last)
{
    // O(N*lgN) complexity sorting
}

template <typename T> struct AlwaysFalse : std::false_type {};

template <typename Iterator>
typename std::enable_if<
    !std::is_same<typename std::iterator_traits<Iterator>::iterator_category, std::random_access_iterator_tag>::value
    >::type
    sorty(Iterator first, Iterator last)
{
    // other sorting algorithm or print out a user-friendly error
    static_assert(AlwaysFalse<Iterator>{}, "Iterator must be a random-access iterator!");
}
Run Code Online (Sandbox Code Playgroud)

演示2

其中enable_ifis_same是C++ 11的类型特点,在C++ 03可以被定义如下:

template <bool b, typename T = void>
struct enable_if {};
template <typename T>
struct enable_if<true, T> { typedef T type; };
template <typename T, typename U>
struct is_same { static const bool value = false; };
template <typename T, typename U>
const bool is_same<T, U>::value;
template <typename T>
struct is_same<T, T> { static const bool value = true; };
template <typename T>
const bool is_same<T, T>::value;
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您只想检查at成员函数的存在,并根据它做出编译时决策,您可能希望使用表达式SFINAE技术:

template <typename Container>
auto sorty_helper(Container&& container, int)
    -> decltype(void(std::forward<Container>(container).at(0)))
{
    // O(N*lgN) complexity sorting
}

template <typename Container>
void sorty_helper(Container&& container, void*)
{
    // O(N*N) complexity sorting
}

template <typename Container>
void sorty(Container&& container)
{
    sorty_helper(std::forward<Container>(container), 0);
}
Run Code Online (Sandbox Code Playgroud)

演示3

在C++ 03中,验证给定签名的成员函数的存在需要手写特征:

template <typename T>
struct has_at
{
    typedef char (&yes)[1];
    typedef char (&no)[2];

    template <typename U, U u>
    struct SFINAE {};

    template <typename U>
    static yes test(SFINAE<typename U::reference(U::*)(std::size_t), &U::at>*);

    template <typename U>
    static no test(...);

    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
Run Code Online (Sandbox Code Playgroud)

可以与enable_if以下组合使用:

template <bool b, typename T = void>
struct enable_if {};

template <typename T>
struct enable_if<true, T> { typedef T type; };

template <typename Container>
typename enable_if<has_at<Container>::value>::type
    sorty(Container& container)
{
    // O(N*lgN) complexity sorting
}

template <typename Container>
typename enable_if<!has_at<Container>::value>::type
    sorty(Container& container)
{
    // O(N*N) complexity sorting
}
Run Code Online (Sandbox Code Playgroud)

演示4