C++实战:手撕类似于vector的容器(逆序算法、排序算法等)

发布于:2024-12-22 ⋅ 阅读:(13) ⋅ 点赞:(0)

1、使用C++泛型编程实现类似于vector的容器类ArrContainer

直接上代码:可作读者参考

#pragma once
#include <exception>
template<typename T>
class ArrContainer
{
private:
	T* m_data; //存放数据
	int m_iCap; //容器的容量
	int m_iLen; //容器中元素的数量
	T* m_pHead; //头指针
	T* m_pRear; //尾部指针
public:
	ArrContainer() {
		m_iCap = 100;
		m_data = new T[m_iCap];
		m_iLen = 0;
		m_pHead = m_pRear = nullptr;
	}
	ArrContainer(int iLen)
	{
		if (iLen < 0)
		{
			m_data = nullptr;
			m_pHead = nullptr;
			m_pRear = nullptr;
			m_iLen = 0;
			m_iCap = 0;
		}
		m_iLen = iLen;
	}
	ArrContainer(T* data, int iLen)
	{
		//step01: Judge the parameters whether are illegal
		if (nullptr == data || iLen <= 0)
		{
			m_data = nullptr;
			m_pHead = nullptr;
			m_pRear = nullptr;
			m_iCap = 0;
			m_iLen = 0;
			return;
		}

		//step02: Allocate memory for data
		m_iCap = iLen + 100;
		m_iLen = iLen;
		m_data = new T[m_iCap];

		//step03: Copy data
		for (int i = 0; i < m_iLen; ++i)
		{
			m_data[i] = data[i];
		}

		m_pHead = &m_data[0];
		m_pRear = &m_data[m_iLen - 1];
	}
	~ArrContainer()
	{
		if (m_data != nullptr)
		{
			delete[] m_data;
			m_data = nullptr;
		}
	}
public:
	bool push_back(const T& elem)
	{
		if (m_iLen < m_iCap)
		{
			m_data[m_iLen - 1] = elem;
		}
		m_pRear++;
	}
	T& operator[](int index)
	{
		if (index < 0 || index >= m_iLen)
		{
			exit(-1);
		}
		return m_data[index];
		
	}
	int size()
	{
		return m_iLen;
	}
	int capacity()
	{
		return m_iCap;
	}
	bool resize(int iLenNew)
	{
		return false;
	}

	// 逆序算法
	bool reverse()
	{
		T tmp;
		while (m_pHead < m_pRear)
		{
			tmp = *m_pHead;
			*m_pHead = *m_pRear;
			*m_pRear = tmp;
			m_pHead++;
			m_pRear--;
		}
		m_pHead = &m_data[0];
		m_pRear = &m_data[m_iLen - 1];

		return true;
	}
};