为什么 std::span 是一个指针 + 大小而不是两个迭代器
Why is std::span a pointer + size and not two iterators
似乎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::span
是std::list
或std::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>
。
相关文章:
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 如果我的容器位于两个现有值之间,那么伪造迭代器类别是否合理
- 如何复制只有两个迭代器的数据?
- 如何以链式方式在两个容器上构建迭代器
- 为什么 std::span 是一个指针 + 大小而不是两个迭代器
- 设计具有两个指向嵌套对象的指针的迭代器
- 声明一个模板函数,该函数接收两个泛型迭代器作为参数
- C++从两个迭代器创建列表对
- 在两个层迭代器中超载 产生奇怪的错误
- 如何在C++中比较两个非随机访问迭代器
- 如何定义模板函数,该功能在C 中占用两个迭代器
- 指向同一项的两个映射迭代器是否保证相等
- 迭代两个向量比boost_foreach迭代器更快
- 是同一集合上的两个不同的迭代器
- 如何获取两个迭代器之间的元素总数
- 使用STL迭代器的两个循环
- 给定同一数据结构的两个迭代器,如何检查哪个迭代器在另一个之前
- 如何在VS2013上比较两个迭代器进行单元测试
- <algorithm>在同一输入迭代器范围内并排运行两个
- C++矢量迭代器:比较和擦除两个元素