为什么 std::span 是一个指针 + 大小而不是两个迭代器

Why is std::span a pointer + size and not two iterators

本文关键字:迭代器 两个 一个 span std 为什么 指针      更新时间:2023-10-16

似乎C++20中的std::span定义类似于

template<class T>
class span
{
T* begin;
size_t count;
};

而不是

template<class Iter>
class span
{
Iter begin;
Iter end;
};

哪个更通用(适用于 std::list、std::map 等)?

std::span<T>

的全部意义在于查看连续数据。pair<T*, size_>(或类似的东西)是表示该视图的正确方式。你不能有一个std::spanstd::liststd::map的视图,所以想出一种方法来表示它是没有意义的。关键是要成为一种常见的词汇类型,只接受连续的数据。

有效地擦除类型span也非常重要。span<int>可以指动态分配的int[20]vector<int>int[],也可以指llvm::SmallVector<int>或...不管它来自哪里,你只有一个类型:"查看一些连续的int

"。的确,pair<Iter, Iter>(或者更一般地说,pair<Iter, Sentinel>)是一个更通用的表示,适用于更多的容器。C++20 中也有这样的东西,它被称为std::ranges::subrange<I, S>.但请注意,我们没有类型擦除方面...map<K, V>上的subrange与具有相同value_type的不同容器上的subrange具有不同的类型,例如list<pair<K const, V>>vector<pair<K const, V>>multimap<K, V>