Files
dl_old/dl/base/dl_vector2.h
T
2023-08-27 23:16:04 +08:00

197 lines
2.9 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file dl_vector2.h
* @brief 2维vector
*
*
* @version 1.0
* @author lveyou
* @date 23-07-09
*
* @note 提供行指针,避免乘法计算
* @note 设计为深拷贝,与std::vector一致
* @note 访问以y,x
* @note 注意auto迭代是全部,而不是按行
*/
#pragma once
#include <cstddef>
#include <vector>
#include <cassert>
#include "dl_type.h"
#include "base/dl_range_accumulate.h"
namespace dl
{
template<typename T>
class Vector2
{
public:
/**
* @brief 空构造
*/
Vector2() :
_w{ 0 }
{}
/**
* @brief 以指定大小构造
*/
Vector2(const Size& size)
{
_init(size);
}
/**
* @brief 以指定大小构造,并传入指针赋值初始化
*/
Vector2(const Size& size, const T* p)
{
_init(size);
for (size_t i = 0; i < _data.size(); ++i)
{
_data[i] = *(p + i);
}
}
/**
* @brief 调整为指定大小
* @note 保留原有值 todo
*/
void Resize(const Size& size)
{
assert(_w == 0);
_init(size);
}
/**
* @brief 返回第j行
*/
T* operator[](std::size_t j)
{
assert(j < _ptrLine.size());
return _ptrLine[j];
}
/**
* @brief 返回第j行
*/
const T* operator[](std::size_t j) const
{
assert(j < _ptrLine.size());
return _ptrLine[j];
}
/**
* @brief 返回第j行 第i个
* @note 与传统[]访问一致,先访问行
*/
/*T& operator[](std::size_t j, std::size_t i)
{
assert(j < _ptrLine.size());
assert(i < _w);
return _ptrLine[j][i];
}*/
const T& Get(std::size_t j, std::size_t i) const
{
assert(j < _ptrLine.size());
assert(i < _w);
return _ptrLine[j][i];
}
/**
* @brief 填充值
*/
void Fill(const T& v)
{
for (auto& iter : _data)
iter = v;
}
/**
* @brief 插入行
* @note 会使 y+1
*/
void PushBack(std::vector<T>& vec)
{
assert(vec.size() == _w);
_data.insert(_data.end(), vec.begin(), vec.end());
_rebuild_ptr_line(_ptrLine.size() + 1);
}
bool IsEmpty() const { return _data.empty(); }
const std::byte* GetBuffer() const
{
return (const std::byte*)_data.data();
}
T* GetData()
{
return _data.data();
}
const T* GetData() const
{
return _data.data();
}
unsigned GetWidth() const
{
return _w;
}
unsigned GetHeight() const
{
return (unsigned)_ptrLine.size();
}
Size GetSize() const
{
return { GetWidth(), GetHeight() };
}
// 由于标准库 size与 length等价,不使用length命令
unsigned GetSizeMul() const
{
return GetWidth() * GetHeight();
}
size_t GetSizeByte()
{
return _data.size() * sizeof(T);
}
auto begin()
{
return _data.begin();
}
auto end()
{
return _data.end();
}
private:
std::vector<T> _data;
unsigned _w;// 宽
std::vector<T*> _ptrLine; // 行指针
void _init(const Size& size)
{
_w = size[0];
_data.resize(Accumulate::Mul(size));
_rebuild_ptr_line(size[1]);
}
// 重建行指针
void _rebuild_ptr_line(std::size_t h)
{
_ptrLine.resize(h);
for (std::size_t i = 0; i < _ptrLine.size(); ++i)
_ptrLine[i] = _data.data() + i * _w;
}
};
}