C++20中的span容器及用法小结

  template

  class span {

  public:

  // 定义迭代器类型

  using iterator = T*;

  using const_iterator = const T*;

  // 构造函数

  constexpr span() noexcept : data_(nullptr), size_(0) {}

  constexpr span(T* ptr, std::size_t count) : data_(ptr), size_(count) {}

  template

  constexpr span(T(&arr)[N]) noexcept : data_(arr), size_(N) {}

  template

  constexpr span(Container& c) noexcept : data_(c.data()), size_(c.size()) {}

  // 拷贝构造函数和拷贝赋值运算符

  constexpr span(const span& other) noexcept = default;

  span& operator=(const span& other) noexcept = default;

  // 访问元素和迭代器操作

  constexpr T* data() const noexcept { return data_; }

  constexpr std::size_t size() const noexcept { return size_; }

  constexpr bool empty() const noexcept { return size_ == 0; }

  constexpr T& operator[](std::size_t idx) const { return data_[idx]; }

  constexpr T& front() const { return data_[0]; }

  constexpr T& back() const { return data_[size_-1]; }

  constexpr iterator begin() const noexcept { return data_; }

  constexpr iterator end() const noexcept { return data_ + size_; }

  constexpr const_iterator cbegin() const noexcept { return data_; }

  constexpr const_iterator cend() const noexcept { return data_ + size_; }

  private:

  T* data_; // 元素指针

  std::size_t size_; // 元素数量

  };