Murilo :P

Computação, programação, web e afins :)

Archive for the ‘Estruturas de Dados’ Category

Static Template Matrix – uma abordagem diferente

com 2 comentários

Static Template Matrix?

C++
De fato eu nunca vi esse nome em outro lugar, mas foi o nome que eu pensei que se aproxima mais da implementação que veremos nesse post.

Trata-se template de uma matriz (matrix) de duas dimensões de tamanho constante (static). Uma das diferenças dessa matriz é que ao invés de se usar o convencional operator[] para acessar os elementos, nessa abordagem iremos utilizar o operator().

Motivações

Na realidade, não tem muito mais utilidades práticas do que matrizes normais. Pode ser que pode servir em algo para você. Então minha motivação é puramente de aprendizagem, principalmente da linguagem.

matrix.h

#ifndef _CLASS_MATRIX_H__
#define _CLASS_MATRIX_H__

/**
 * matrix.h
 * Defines a template type 'matrix' wich is a constant-sized 2-dimensioned
 * 	matrix and generic typed elements.
 *
 * author: Murilo Adriano Vasconcelos
 * website: http://murilo.wordpress.com
 */

template
class matrix
{
    //data matrix
    T data[R][C];

    public:
    //type of the current matrix
    typedef matrix matrix_t;

    //quantity of rows
    const unsigned rows;
    //quantity of columns
    const unsigned columns;

    //default ctor
    matrix(): rows(R), columns(C) {};

    /*ctor wich initializes the matrix filled
      with 'value' elements */
    matrix(const T& value);

    //copy ctor: copies the matrix 'tocopy'
    matrix(const matrix_t& tocopy);

    /*gets and/or set the value of the element
      in the row 'i', column 'j' */
    T& operator()(unsigned i, unsigned j);

    /*gets the value of the element in the
      row 'i', column 'j' */
    const T& operator()(unsigned i, unsigned j) const;

    //copy operator
    matrix_t& operator=(const matrix_t& tocopy);
};

/* class functions definition */

    template
matrix::matrix(const matrix& tocopy): rows(R), columns(C)
{
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++)
            data[i][j] = tocopy(i, j);
}

    template
matrix::matrix(const T& value): rows(R), columns(C)
{
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++)
            data[i][j] = value;
}

template
    matrix&
matrix::operator=(const matrix& tocopy)
{
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++)
            data[i][j] = tocopy(i, j);

    return *this;
}

    template
T& matrix::operator()(unsigned i, unsigned j)
{
    return data[i][j];
}

template
const T& matrix::operator()(unsigned i, unsigned j) const
{
    return data[i][j];
}

#endif

main.cpp

#include "matrix.h" //our matrix
#include  //cout'ing
#include    //for strings

int main()
{
        //declares a 3x3 matrix filled with "nil"
        matrix mat("nil");

        //modifies the value in the position (1, 1) to C++
        mat(1, 1) = "C++";

        //we can use the const atribbutes rows and columns
        //to check our limits
        for (int i = 0; i < mat.rows; i++) {
                for (int j = 0; j < mat.columns; j++) {
                        //getting, setting the value of matrix elements
                        //is the same way
                        std::cout << mat(i, j) << ' ';
                }

                std::cout << '\n';
        }

        std::cout << '\n';

        matrix ones(1), identity;
        //copy
        identity = ones;

        //so silly
        for (int i = 0; i < identity.rows; i++) {
                for (int j = i; j < identity.columns; j++) {
                        if (i != j) {
                                identity(i, j) = identity(j, i) = 0;
                        }
                }
        }

        for (int i = 0; i < identity.rows; i++) {
                for (int j = 0; j < identity.columns; j++) {
                        std::cout << identity(i, j) << ' ';
                }

                std::cout << '\n';
        }

        return 0;
}

Como vocês puderam notar, a forma de acesso e modificação (get, set) dos elementos da matriz é da mesma forma. Outra coisa que podemos notar é que passamos o tipo e a quantidade de linhas e colunas direto no template. A quantidade de linha e colunas passada deve ser uma constante.

Bom, até mais.

obs.: Eu odeio profundamente o source highlight bugado do WordPress que converte todos os meus < e > e etc. para &lt; &gt;. Por isso os fontes acima não estão com hl.

Agora sim, até mais.

Escrito por Murilo Adriano

Segunda-feira 12 de Outubro de 2009 em 21:08

Publicado em C/C++, Estruturas de Dados, Programação

Etiquetado com , ,

Smart Pointers: Os Ponteiros Espertos do C++

com 2 comentários

C++E aí pessoal, como prometido, vou falar sobre Smart Pointers em C++.
Neste post irei abordar smart pointers, o que são, como funcionam e para que são usados, além de mostrar um exemplo de implementação de smart pointers.

1. Introdução:

O que são Smart Pointers?

Smart pointers são implementações feitas para facilitar e ajudar no manuseamento de ponteiros. Para serem mais “inteligentes” que os ponteiros normais, os smart pointers precisam fazer coisas que os ponteiros normais não fazem. Leia o resto deste post »

Escrito por Murilo Adriano

Segunda-feira 15 de Dezembro de 2008 em 14:18

Publicado em C/C++, Estruturas de Dados, Programação

Etiquetado com ,

Vector? Deque? Stack? Map? List? Como escolher o container STL correto?

com 2 comentários

Esses dias atrás no canal #c++ da Freenode encontrei um diagrama que achei bem interessante ter guardado. Ele ajuda a escolher qual container da STL do C++ escolher quando a gente for fazer nossos programinhas ou projetões :) .

C++ STL Containers

C++ STL Containers

Escrito por Murilo Adriano

Quinta-feira 25 de Setembro de 2008 em 02:03