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

use*_*329 5 c++ c++20 std-span

看来std::spanC ++ 20中的定义与

template<class T>
class span
     {
     T* begin;
     size_t count;
     };
Run Code Online (Sandbox Code Playgroud)

并不是

template<class Iter>
class span
     {
     Iter begin;
     Iter end;
     };
Run Code Online (Sandbox Code Playgroud)

哪个更通用(可与std :: list,std :: map等配合使用)?

Bar*_*rry 8

整个观点std::span<T>是要查看连续数据。pair<T*, size_>(或类似的东西)是表示该视图的正确方法。您不能以std::spana std::list或a 为视角std::map,因此想出一种表示它的方法没有任何意义。关键是要成为通用词汇表类型,以便仅接受连续数据。

It's also very important span is effectively type-erased. A span<int> could refer into a int[20] or a vector<int> or a int[] that is dynamically allocated somewhere or a llvm::SmallVector<int> or a ... It doesn't matter where it comes from, you just have the one type that is: "view over some contiguous ints".

It is true that pair<Iter, Iter> (or, more generally, pair<Iter, Sentinel>) is a more general representation that would work for more containers. There is such a thing in C++20 as well, it's called std::ranges::subrange<I, S>. But note here that we don't have the type-erasure aspect... a subrange over a map<K, V> will have a different type than a subrange over a different container with the same value_type, like list<pair<K const, V>> or vector<pair<K const, V>> or multimap<K, V>.

  • @ user877329:“ *但是您可以随后在任何要使用跨度的地方使用子范围。*”不,您不能。您可以将“ span”的数据传递给C API。您不能使用任意迭代器子范围来做到这一点。 (2认同)