/*
 * Instituto Superior de Engenharia do Porto
 *
 * Estruturas de Informação
 *
 * 2000/2001
 *
 * ------------------------------------------
 *
 * Classe de Vector de Inteiros V2
 *		- aumento dinamico do tamanho do vector
 *
 * vectorint.cpp
 *
 */

#include "vectorint.h"
#include "..\ei-include\erro.h"
#include <memory.h>


const int PER_CRESCE = 10;


VectorInteiros::VectorInteiros(int nCount /* = DIM_INICIAL */)
{
	if (nCount <= 0)
	{
		m_nTamanhoReal = m_count = -1;
		m_vector = NULL;
		return;
	}

	m_nTamanhoReal = m_count = nCount;
	m_vector = new int[nCount];
	if (m_vector == NULL)
		//throw Erro(SEM_MEMORIA);
		m_count = 0;
}

VectorInteiros::VectorInteiros(const VectorInteiros& o)
{
	m_vector = NULL;
	copia(o);
}

VectorInteiros::~VectorInteiros()
{
	if (m_vector != NULL)
		delete [] m_vector;
}
	
bool VectorInteiros::colocar(int pos, int valor)
{
	if (pos < 0 || pos >= m_count)
		crescer(pos);
	
	m_vector[pos] = valor;
	return true;
}

int VectorInteiros::obter(int pos) const
{
	if (pos < 0 || pos >= m_count)
		throw Erro(POSICAO_INVALIDA);
	
	return m_vector[pos];
}

int VectorInteiros::tamanho() const
{
	return m_count;
}

bool VectorInteiros::crescer(int pos)
{
	if (pos < m_nTamanhoReal)
		m_count = pos + 1;	
	else
	{
		m_nTamanhoReal = pos + PER_CRESCE;
		int* pV = new int[m_nTamanhoReal];
		if (pV == NULL)
			throw Erro(SEM_MEMORIA);

		//memset(pV, 0, m_nTamanhoReal*sizeof(int));
		
		//memcpy(pV, m_vector, (size_t)(m_count*sizeof(int)));
		for(int i = 0; i < m_count; i++)
			pV[i] = m_vector[i];

		delete [] m_vector;
		m_vector = pV;

		m_count = pos + 1;
	}

	return true;
}

int& VectorInteiros::operator[](int iPos)
{
	if (iPos < 0 || iPos >= m_count)
		throw Erro(POSICAO_INVALIDA);
	
	return m_vector[iPos];
}

VectorInteiros& VectorInteiros::operator=(const VectorInteiros& o)
{
	copia(o);
	return *this;
}

void VectorInteiros::copia(const VectorInteiros& o)
{
	if (m_vector != NULL)
		delete [] m_vector;

	m_nTamanhoReal = m_count = o.tamanho();
	m_vector = new int[o.tamanho()];
	for(int i = 0; i < o.tamanho(); i++)
		m_vector[i] = o.obter(i);
}

bool operator==(const VectorInteiros& a, const VectorInteiros& b)
{
	if (a.tamanho() != b.tamanho())
		return false;

	for(int i = 0; i < a.tamanho(); i++)
		if (a.obter(i) != b.obter(i))
			return false;

	return true;
}
