TProcura
Biblioteca em C++ para testes paramétricos de algoritmos, e coleção de algoritmos de procura e otimização
Loading...
Searching...
No Matches
TVector< Item > Class Template Reference

#include <TVector.h>

Collaboration diagram for TVector< Item >:

Public Member Functions

TVectoroperator+= (const TVector &o)
 Concatena outro vetor a este.
 
TVectoroperator+= (std::initializer_list< Item > init)
 Adiciona múltiplos elementos ao final do vetor.
 
TVector< Item > & operator+= (const char *str)
 Acrescenta elementos a partir de uma string no formato de lista.
 
Construtores e Destrutor
 TVector (int size=0)
 Construtor.
 
 TVector (int size, Item const *init)
 Constrói um vetor pré-carregado a partir de um array.
 
virtual ~TVector () noexcept
 Destrutor.
 
Construtores e operadores especiais
 TVector (const TVector &o)
 Construtor de cópia.
 
TVectoroperator= (const TVector &o)
 Operador de atribuição por cópia.
 
 TVector (TVector &&o) noexcept
 Construtor de movimentação.
 
 TVector (std::initializer_list< Item > init)
 Constrói um vetor a partir de uma lista de inicialização.
 
 TVector (const char *str)
 Constrói um vetor de inteiros a partir de uma string no formato de lista.
 
TVectoroperator= (TVector &&o) noexcept
 Operador de atribuição por movimentação.
 
Acesso a Elementos
TVector< Item > & Add (Item a)
 
TVector< Item > & Insert (Item a, int index=0)
 Insere um único elemento na posição indicada.
 
TVector< Item > & Insert (TVector< Item > &v, int index=0)
 Insere um vetor de itens na posição indicada.
 
TVector< Item > & Push (Item a)
 
Item & Pop ()
 
Item & operator[] (int i)
 Acesso por índice com auto-expansão.
 
const Item & operator[] (int i) const
 Acesso constante por índice sem modificação de tamanho.
 
Item * Data ()
 Acesso direto.
 
const Item * Data () const
 Acesso direto constante.
 
Item & First ()
 
Item & Last ()
 
int Count () const
 
bool Empty () const
 
TVector< Item > & Count (int value)
 Ajusta o tamanho lógico do vetor para value.
 
Item & Random ()
 
Operações de Conjunto
TVector< Item > & BeASet ()
 Converte o vetor num conjunto: remove duplicados e ordena.
 
TVector< Item > & Union (const TVector< Item > &v)
 Realiza a união deste conjunto com outro.
 
TVector< Item > & Intersection (const TVector< Item > &v)
 Interseção deste conjunto com outro.
 
TVector< Item > & Difference (const TVector< Item > &v)
 Diferença deste conjunto em relação a outro.
 
bool Equal (const TVector< Item > &v) const
 Verifica se dois vetores-conjunto são iguais.
 
bool Contained (const TVector< Item > &v) const
 Verifica se este conjunto está contido no outro.
 
Algoritmos e Modificadores
TVector< Item > & Delete (int i)
 Remove o elemento na posição i deslocando os seguintes.
 
TVector< Item > & Remove (Item const &i)
 Remove todas as ocorrências de um dado elemento.
 
int Find (Item &i, bool binary=false, int left=0, int right=-1)
 Procura um elemento no vetor.
 
TVector< Item > & Replace (Item const &iold, Item const &inew)
 Substitui todas as ocorrências de um valor antigo por um novo.
 
TVector< Item > & Sort (TVector< int > *idxvect=nullptr)
 Ordena todo o vetor, opcionalmente devolvendo índices ordenados.
 
void Sort (int start, int end=-1)
 Ordena um subintervalo [start,end] do vetor.
 
TVector< Item > & RandomOrder ()
 Coloca os elementos em ordem aleatória (Fisher–Yates shuffle).
 
TVector< Item > & Invert ()
 Inverte a ordem dos elementos no vetor.
 
TVector< Item > & Reset (Item const &i)
 Preenche todo o vetor com um mesmo valor.
 
int Distance (TVector< Item > &v, int type=0)
 Calcula várias métricas de “distância” entre vetores.
 
Iteradores
Item * begin () noexcept
 
Item * end () noexcept
 
const Item * begin () const noexcept
 
const Item * end () const noexcept
 

Static Public Attributes

static Item erro
 Valor retornado em casos de acesso inválido.
 

Operadores Adicionais

TVector< Item > & operator+= (const Item &x)
 
TVector< Item > & operator-= (const Item &x)
 
TVector< Item > operator+ (TVector< Item > a, const TVector< Item > &b)
 
bool operator== (const TVector< Item > &a, const TVector< Item > &b)
 
bool operator!= (const TVector< Item > &a, const TVector< Item > &b)
 

Detailed Description

template<class Item>
class TVector< Item >

Definition at line 26 of file TVector.h.

Constructor & Destructor Documentation

◆ TVector() [1/6]

template<class Item >
TVector< Item >::TVector ( int  size = 0)

Construtor.

Construtor. Se size>0, aloca capacidade inicial.

Parameters
sizeCapacidade inicial do vetor. Se zero, não aloca buffer até ao primeiro acesso.

Definition at line 394 of file TVector.h.

◆ TVector() [2/6]

template<class Item >
TVector< Item >::TVector ( int  size,
Item const *  init 
)

Constrói um vetor pré-carregado a partir de um array.

Construtor com inicialização de elementos a partir de init.

Parameters
sizeNúmero de elementos a copiar de init.
initPonteiro para o array de origem.
  • Se size > 0, redimensiona a capacidade via Size().
  • Copia cada elemento de init para o vetor interno.
  • Ajusta count para size.

Definition at line 412 of file TVector.h.

◆ ~TVector()

template<class Item >
TVector< Item >::~TVector ( )
virtualnoexcept

Destrutor.

Destrutor, libera o buffer interno.

Liberta o buffer interno alocado para v.

Definition at line 430 of file TVector.h.

◆ TVector() [3/6]

template<class Item >
TVector< Item >::TVector ( const TVector< Item > &  o)

Construtor de cópia.

Parameters
oVetor a copiar.

Definition at line 441 of file TVector.h.

◆ TVector() [4/6]

template<class Item >
TVector< Item >::TVector ( TVector< Item > &&  o)
noexcept

Construtor de movimentação.

Parameters
oVetor temporário a mover.

Transfere o buffer interno sem copiar elementos.

Parameters
oVetor temporário a mover.

Transfere o buffer interno sem cópia de elementos.

Definition at line 471 of file TVector.h.

◆ TVector() [5/6]

template<class Item >
TVector< Item >::TVector ( std::initializer_list< Item >  init)
inline

Constrói um vetor a partir de uma lista de inicialização.

Parameters
initLista de elementos a copiar para o vetor.

Definition at line 99 of file TVector.h.

Here is the call graph for this function:

◆ TVector() [6/6]

template<class Item >
TVector< Item >::TVector ( const char *  str)
inline

Constrói um vetor de inteiros a partir de uma string no formato de lista.

Parameters
strString com a lista de inteiros ou intervalos.

Sintaxe suportada (sem espaços):

  • "A" ou "A,B,C" : valores individuais separados por vírgulas
  • "A:B" : intervalo de A até B (passo 1)
  • "A:B:C" : intervalo de A até B com passo C

Exemplos:

TVector<int> v("1,3,5"); // {1,3,5}
TVector<int> v("0:10:2,15"); // {0,2,4,6,8,10,15}
  • Valores inválidos ou passo <= 0 são ajustados para passo = 1.
  • Se A > B, a ordem é invertida.
  • Remove duplicados e ordena no final (BeASet()).

Definition at line 126 of file TVector.h.

Member Function Documentation

◆ Add()

template<class Item >
TVector< Item > & TVector< Item >::Add ( Item  a)
inline

Adiciona a no final do vetor.

Definition at line 178 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BeASet()

template<class Item >
TVector< Item > & TVector< Item >::BeASet ( )

Converte o vetor num conjunto: remove duplicados e ordena.

Remove duplicados e ordena os elementos.

  • Ordena o vetor completo.
  • Percorre e elimina valores consecutivos iguais.
  • Atualiza count para o novo número de elementos.
    Returns
    Referência ao próprio vetor.

Definition at line 836 of file TVector.h.

Here is the caller graph for this function:

◆ begin() [1/2]

template<class Item >
const Item * TVector< Item >::begin ( ) const
inlinenoexcept

Definition at line 318 of file TVector.h.

◆ begin() [2/2]

template<class Item >
Item * TVector< Item >::begin ( )
inlinenoexcept

Definition at line 316 of file TVector.h.

Here is the caller graph for this function:

◆ Contained()

template<class Item >
bool TVector< Item >::Contained ( const TVector< Item > &  other) const

Verifica se este conjunto está contido no outro.

Verifica se este conjunto está contido em v (ordenados).

Parameters
otherConjunto suposto “contedor” (ordenado).
Returns
true se todos os elementos deste vetor aparecem em other.

Definition at line 953 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Count() [1/2]

template<class Item >
int TVector< Item >::Count ( ) const
inline

Número de elementos presentes.

Definition at line 227 of file TVector.h.

◆ Count() [2/2]

template<class Item >
TVector< Item > & TVector< Item >::Count ( int  value)
inline

Ajusta o tamanho lógico do vetor para value.

Realoca o buffer interno caso value exceda a capacidade atual. Os novos elementos entre a capacidade antiga e value não são inicializados.

Parameters
valueNovo número de elementos do vetor.
Returns
Referência ao próprio vetor (permite encadear chamadas).

Definition at line 241 of file TVector.h.

◆ Data() [1/2]

template<class Item >
Item * TVector< Item >::Data ( )
inline

Acesso direto.

Definition at line 216 of file TVector.h.

◆ Data() [2/2]

template<class Item >
const Item * TVector< Item >::Data ( ) const
inline

Acesso direto constante.

Definition at line 218 of file TVector.h.

◆ Delete()

template<class Item >
TVector< Item > & TVector< Item >::Delete ( int  i)

Remove o elemento na posição i deslocando os seguintes.

Deleta o elemento na posição i.

Parameters
iÍndice do elemento a eliminar (0 ≤ i < count).
Returns
Referência ao próprio vetor.

Definition at line 817 of file TVector.h.

Here is the caller graph for this function:

◆ Difference()

template<class Item >
TVector< Item > & TVector< Item >::Difference ( const TVector< Item > &  other)

Diferença deste conjunto em relação a outro.

Diferença com v (vetores em conjunto).

Parameters
otherConjunto cujos elementos serão subtraídos.
Returns
Referência ao próprio vetor já representando a diferença.

Definition at line 910 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Distance()

template<class Item >
int TVector< Item >::Distance ( TVector< Item > &  other,
int  type = 0 
)

Calcula várias métricas de “distância” entre vetores.

Calcula a distância entre este vetor e v.

Parameters
typeTipo de distância:
  • 0: correspondência exata (O(N))
  • 1: distância de desvio (O(N))
  • 2: R-distance (O(N^2))
  • 3: edit distance (O(N^2))
otherOutro vetor para comparação.
typeTipo de métrica:
  • 0: diferença exata de posições (O(N))
  • 1: soma de desvios absolutos (O(N))
  • 2: R-type distance (O(N²))
  • 3: edit distance (Levenshtein) (O(N²))
Returns
Valor inteiro representando a distância.

Definition at line 1040 of file TVector.h.

Here is the call graph for this function:

◆ Empty()

template<class Item >
bool TVector< Item >::Empty ( ) const
inline

Verifica se o vetor está vazio.

Definition at line 230 of file TVector.h.

Here is the caller graph for this function:

◆ end() [1/2]

template<class Item >
const Item * TVector< Item >::end ( ) const
inlinenoexcept

Definition at line 319 of file TVector.h.

◆ end() [2/2]

template<class Item >
Item * TVector< Item >::end ( )
inlinenoexcept

Definition at line 317 of file TVector.h.

Here is the caller graph for this function:

◆ Equal()

template<class Item >
bool TVector< Item >::Equal ( const TVector< Item > &  other) const

Verifica se dois vetores-conjunto são iguais.

Verifica igualdade com v (vetores em conjunto e ordenados).

Parameters
otherOutro vetor a comparar (deve estar ordenado e sem duplicados).
Returns
true se tamanhos e elementos coincidem; false caso contrário.

Definition at line 937 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Find()

template<class Item >
int TVector< Item >::Find ( Item &  i,
bool  binary = false,
int  left = 0,
int  right = -1 
)

Procura um elemento no vetor.

Procura i; se binary=true faz busca binária em [left,right].

Parameters
iReferência ao item a procurar.
binarySe true, faz busca binária (vetor deve estar ordenado).
leftÍndice inicial da busca binária (opcional).
rightÍndice final da busca binária (opcional).
Returns
Índice do elemento se encontrado, ou -1 caso contrário.

Definition at line 567 of file TVector.h.

Here is the caller graph for this function:

◆ First()

template<class Item >
Item & TVector< Item >::First ( )
inline

Retorna o primeiro elemento ou erro se vazio.

Definition at line 221 of file TVector.h.

Here is the caller graph for this function:

◆ Insert() [1/2]

template<class Item >
TVector< Item > & TVector< Item >::Insert ( Item  a,
int  index = 0 
)

Insere um único elemento na posição indicada.

Insere um elemento a na posição index, deslocando os seguintes.

Parameters
aElemento a inserir.
indexÍndice de inserção (defaults to end if <0).
Returns
Referência ao próprio vetor após inserção.

Definition at line 1002 of file TVector.h.

Here is the caller graph for this function:

◆ Insert() [2/2]

template<class Item >
TVector< Item > & TVector< Item >::Insert ( TVector< Item > &  src,
int  index = 0 
)

Insere um vetor de itens na posição indicada.

Insere todos os elementos de v começando na posição index.

Parameters
srcVetor cujos elementos serão inseridos.
indexÍndice onde começa a inserção (defaults to end if <0).
Returns
Referência ao próprio vetor após inserção.

Definition at line 976 of file TVector.h.

Here is the call graph for this function:

◆ Intersection()

template<class Item >
TVector< Item > & TVector< Item >::Intersection ( const TVector< Item > &  other)

Interseção deste conjunto com outro.

Interseção com v (vetores em conjunto).

Parameters
otherConjunto contra o qual intersectar (ordenado).
Returns
Referência ao próprio vetor já representando a interseção.

Definition at line 884 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Invert()

template<class Item >
TVector< Item > & TVector< Item >::Invert ( )

Inverte a ordem dos elementos no vetor.

Inverte a ordem atual dos elementos.

Returns
Referência ao próprio vetor.

Definition at line 1020 of file TVector.h.

Here is the caller graph for this function:

◆ Last()

template<class Item >
Item & TVector< Item >::Last ( )
inline

Retorna o último elemento ou erro se vazio.

Definition at line 224 of file TVector.h.

Here is the caller graph for this function:

◆ operator+=() [1/4]

template<class Item >
TVector< Item > & TVector< Item >::operator+= ( const char *  str)
inline

Acrescenta elementos a partir de uma string no formato de lista.

Parameters
strString com a lista de inteiros ou intervalos.
  • Apenas disponível para TVector<int>.
  • Sintaxe: "A" ou "A,B,C" ou "A:B" ou "A:B:C".
  • O parsing e a remoção de duplicados/ordenação são feitos apenas dentro da string, não no vetor final.
  • Os elementos são adicionados no final, preservando os já existentes.

Definition at line 171 of file TVector.h.

◆ operator+=() [2/4]

template<class Item >
TVector< Item > & TVector< Item >::operator+= ( const Item &  x)
inline

Adiciona elemento x ao final (alias de Add).

Definition at line 325 of file TVector.h.

Here is the call graph for this function:

◆ operator+=() [3/4]

template<class Item >
TVector< Item > & TVector< Item >::operator+= ( const TVector< Item > &  o)

Concatena outro vetor a este.

Adiciona todos os elementos de o no final deste vetor.

Parameters
oVetor cujos elementos serão adicionados.
Returns
Referência ao próprio vetor.

Adiciona todos os elementos de o no final do vetor atual.

Parameters
oVetor cujos elementos serão adicionados.
Returns
Referência ao próprio vetor.

Definition at line 508 of file TVector.h.

◆ operator+=() [4/4]

template<class Item >
TVector & TVector< Item >::operator+= ( std::initializer_list< Item >  init)
inline

Adiciona múltiplos elementos ao final do vetor.

Parameters
initLista de elementos a adicionar.
Returns
Referência ao próprio vetor.

Definition at line 152 of file TVector.h.

Here is the call graph for this function:

◆ operator-=()

template<class Item >
TVector< Item > & TVector< Item >::operator-= ( const Item &  x)
inline

Remove todas ocorrências de x (alias de Remove).

Definition at line 328 of file TVector.h.

Here is the call graph for this function:

◆ operator=() [1/2]

template<class Item >
TVector< Item > & TVector< Item >::operator= ( const TVector< Item > &  o)

Operador de atribuição por cópia.

Parameters
oVetor a atribuir.
Returns
Referência ao próprio vetor.

Definition at line 452 of file TVector.h.

◆ operator=() [2/2]

template<class Item >
TVector< Item > & TVector< Item >::operator= ( TVector< Item > &&  o)
noexcept

Operador de atribuição por movimentação.

Parameters
oVetor temporário a mover.
Returns
Referência ao próprio vetor.

Definition at line 485 of file TVector.h.

◆ operator[]() [1/2]

template<class Item >
Item & TVector< Item >::operator[] ( int  i)

Acesso por índice com auto-expansão.

Acesso por índice com auto-expansão.

Se i é maior ou igual à capacidade interna (sz), realoca o buffer para size = 2 × (i+1). Se i é maior ou igual ao número de elementos (count), ajusta count = i+1.

Parameters
iÍndice do elemento a aceder (deve ser ≥ 0).
Returns
Referência ao elemento interno v[i].

Definition at line 530 of file TVector.h.

Here is the caller graph for this function:

◆ operator[]() [2/2]

template<class Item >
const Item & TVector< Item >::operator[] ( int  i) const

Acesso constante por índice sem modificação de tamanho.

Acesso constante por índice sem modificação de tamanho.

Se i é inválido (< 0 ou ≥ count), retorna erro.

Parameters
iÍndice do elemento (0 ≤ i < count).
Returns
Const-ref ao elemento v[i] ou TVector<Item>::erro.

Definition at line 546 of file TVector.h.

◆ Pop()

template<class Item >
Item & TVector< Item >::Pop ( )
inline

Remove e retorna o último elemento; em vetor vazio retorna erro.

Definition at line 190 of file TVector.h.

Here is the caller graph for this function:

◆ Push()

template<class Item >
TVector< Item > & TVector< Item >::Push ( Item  a)
inline

Alias de Add.

Definition at line 187 of file TVector.h.

Here is the call graph for this function:

◆ Random()

template<class Item >
Item & TVector< Item >::Random ( )
inline

Retorna um elemento escolhido aleatoriamente.

Definition at line 250 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ RandomOrder()

template<class Item >
TVector< Item > & TVector< Item >::RandomOrder ( )

Coloca os elementos em ordem aleatória (Fisher–Yates shuffle).

Coloca os elementos em ordem aleatória.

Returns
Referência ao próprio vetor.

Definition at line 752 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Remove()

template<class Item >
TVector< Item > & TVector< Item >::Remove ( Item const &  i)

Remove todas as ocorrências de um dado elemento.

Remove todas as ocorrências de i.

Parameters
iReferência ao elemento a remover.
Returns
Referência ao próprio vetor (permite encadear chamadas).

Definition at line 765 of file TVector.h.

Here is the caller graph for this function:

◆ Replace()

template<class Item >
TVector< Item > & TVector< Item >::Replace ( Item const &  iold,
Item const &  inew 
)

Substitui todas as ocorrências de um valor antigo por um novo.

Substitui todas ocorrências de iold por inew.

Parameters
ioldValor a ser substituído.
inewNovo valor que substitui iold.
Returns
Referência ao próprio vetor.

Definition at line 800 of file TVector.h.

◆ Reset()

template<class Item >
TVector< Item > & TVector< Item >::Reset ( Item const &  i)

Preenche todo o vetor com um mesmo valor.

Preenche todos os elementos com i.

Parameters
iValor a atribuir a cada posição.
Returns
Referência ao próprio vetor.

Definition at line 784 of file TVector.h.

Here is the caller graph for this function:

◆ Sort() [1/2]

template<class Item >
void TVector< Item >::Sort ( int  start,
int  end = -1 
)

Ordena um subintervalo [start,end] do vetor.

Ordena apenas o intervalo [start,end].

Parameters
startÍndice inicial (será ajustado a 0 se negativo).
endÍndice final (será ajustado a count-1 se inválido).

Definition at line 620 of file TVector.h.

◆ Sort() [2/2]

template<class Item >
TVector< Item > & TVector< Item >::Sort ( TVector< int > *  idxvect = nullptr)

Ordena todo o vetor, opcionalmente devolvendo índices ordenados.

Ordena e, opcionalmente, preenche vetor de índices idxvect.

Parameters
idxvectSe não nulo, recebe um vetor de índices ordenados em vez de ordenar os elementos.
Returns
Referência ao próprio vetor (permite encadeamento).

Definition at line 597 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Union()

template<class Item >
TVector< Item > & TVector< Item >::Union ( const TVector< Item > &  other)

Realiza a união deste conjunto com outro.

União com v (supõe vetores já em forma de conjunto).

Parameters
otherConjunto a unir (deve estar ordenado e sem duplicados).
Returns
Referência ao próprio vetor já representando a união.

Definition at line 859 of file TVector.h.

Here is the call graph for this function:
Here is the caller graph for this function:

Friends And Related Symbol Documentation

◆ operator!=

template<class Item >
bool operator!= ( const TVector< Item > &  a,
const TVector< Item > &  b 
)
friend

Compara desigualdade de conjuntos.

Definition at line 337 of file TVector.h.

◆ operator+

template<class Item >
TVector< Item > operator+ ( TVector< Item >  a,
const TVector< Item > &  b 
)
friend

Concatena dois vetores, retornando o resultado.

Definition at line 331 of file TVector.h.

◆ operator==

template<class Item >
bool operator== ( const TVector< Item > &  a,
const TVector< Item > &  b 
)
friend

Compara igualdade de conjuntos (usando Equal).

Definition at line 334 of file TVector.h.

Member Data Documentation

◆ erro

template<class Item >
Item TVector< Item >::erro
static

Valor retornado em casos de acesso inválido.

Valor retornado em casos de erro (acesso inválido).

Deve ser definido pelo utilizador do template para o tipo Item.

Definition at line 59 of file TVector.h.


The documentation for this class was generated from the following file: