未知容器的大小

Size of unknown container

我一直读到使用这段代码不太好:

std::vector<T> my_vector;
...
std::sort(my_vector.begin(), my_vector.end());

最好写成:

std::vector<T> my_vector;
...
std::sort(std::begin(my_vector), std::end(my_vector));

因为 std::begin 将适用于所有容器,包括普通数组。

my_vector.size() 的替代方法是什么,它适用于包括普通数组在内的所有容器?

实际上使用 std::begin(my_vector) 不是 正确的做法!如果您想选择自定义点,您宁愿使用

using std::begin;
using std::end;
std::sort(begin(cont), end(cont));

此方法尝试使用 ADL 查找 begin(cont),当找不到合适的版本时,回退到使用 std::begin

遗憾的是,没有 std::size 作为像 std::begin 这样的自定义点的默认值。使用 std::distance():

有点工作
std::distance(begin(cont), end(cont));

但是,对于典型的基于节点的容器,或者更一般地说,对于非随机访问迭代器,这种方法将遍历元素,而不是从存储的值中获取大小。因此,我想你会想要调用 cont.size()。定义一个合适的自定义点会相对简单:

namespace util {
    template <typename C>
    typename C::difference_type size(C const& c) {
        return c.size();
    }
    template <typename T, std::size_t N>
    std::size_t size(T const(&)[N]) {
        return N;
    }
}

正如评论中指出的那样,非成员 size() 功能被添加到 working paper for C++17 (see the bottom of the synopsis in 24.3 [iterator.synoposis]). N4280 是提出更改的论文。本文还提出了函数 empty()data() ,它们也被添加了。所有这些函数都在 <iterator>.

中声明

添加到 C++17 的版本直接在 return 类型的 size() 成员上使用 decltype()。此外,它将函数声明为 constexpr:

template <typename C>
constexpr auto size(C const& c) -> decltype(c.size()) {
    return c.size();
}