76 lines
2.2 KiB
C++
76 lines
2.2 KiB
C++
#pragma once
|
||
#include <array>
|
||
#include <concepts>
|
||
namespace zstd {
|
||
//栈容器,大小可变,只能从std::array安全构造
|
||
template<typename T>
|
||
class svector {
|
||
protected:
|
||
T* m_ptr;
|
||
int m_count;
|
||
int m_capicty;
|
||
public:
|
||
constexpr svector() :m_ptr(nullptr), m_count(0), m_capicty(0) {}
|
||
template<auto N>
|
||
constexpr svector(std::array<T, N>& arr, int count) : m_ptr(arr.data()), m_capicty(N), m_count(count) {}
|
||
constexpr T* front()const noexcept {
|
||
return m_ptr;
|
||
}
|
||
constexpr T* back()const noexcept {
|
||
return m_ptr + m_count;
|
||
}
|
||
constexpr void push_back(const T& t) {
|
||
if (m_count < m_capicty) {
|
||
*(m_ptr + m_count) = t;
|
||
m_count++;
|
||
}
|
||
}
|
||
constexpr operator bool() const noexcept {
|
||
return m_count > 0;
|
||
}
|
||
constexpr bool empty() const noexcept {
|
||
return m_count == 0;
|
||
}
|
||
constexpr int size() const noexcept {
|
||
return m_count;
|
||
}
|
||
constexpr auto begin()const noexcept {
|
||
return iterator{ m_ptr };
|
||
}
|
||
constexpr auto end() const noexcept {
|
||
return iterator{ m_ptr + m_count };
|
||
}
|
||
// Iterator class
|
||
class iterator {
|
||
private:
|
||
const T* ptr;
|
||
|
||
public:
|
||
constexpr iterator(const T* p) : ptr(p) {}
|
||
|
||
// Overload ++ to move to next element
|
||
constexpr iterator& operator++() noexcept {
|
||
++ptr;
|
||
return *this;
|
||
}
|
||
//这里其实是--it,而不是it--
|
||
constexpr iterator& operator--(int) noexcept {
|
||
--ptr;
|
||
return *this;
|
||
}
|
||
constexpr const T* operator->() const noexcept {
|
||
return ptr;
|
||
}
|
||
// Overload * to dereference iterator
|
||
constexpr const T& operator*() const noexcept {
|
||
return *ptr;
|
||
}
|
||
|
||
// Overload != to compare iterators
|
||
constexpr bool operator!=(const iterator& other) const noexcept {
|
||
return ptr != other.ptr;
|
||
}
|
||
};
|
||
};
|
||
}
|