Herculano 0 Denunciar post Postado Março 24, 2009 Olá galera estou fazendo um trabalho da facu no qual eu devo criar uma estrutura de dados para fazer operações com conjuntos de numeros inteiros. TConj.h typedef struct { int tamanho; int *valores; bool boolean; }TConj; void Inicializa (TConj*); int InserirElemento(TConj*, int); void SetElemento (TConj*, int, int); int GetElemento (TConj*, int); int TestaElemento (TConj*, int); TConj GeraConjunto (int); TConj GeraConjuntoSR (int); TConj Num2Conj (int); int Conj2Num (TConj); int Compara (TConj,TConj); void Imprime (TConj); TConj* Uniao (TConj,TConj); TConj* Inter (TConj,TConj); TConj* Subtrair (TConj,TConj); TConj.cpp #include <iostream> using namespace std; #include "TConj.h" #include <math.h> #include <cstdlib> using std::rand; using std::srand; void Inicializa(TConj* a) { int i; a->valores = (int *) malloc (10 * sizeof (int)); for (i=0; i < 10;i++) { a->valores[i]= 0; } if (!a->valores) { a->boolean= false; cout << " Erro - Memória insuficiente. " << endl; } else { a->boolean=true; } } int InserirElemento(TConj* pa, int elemento) { if(pa->boolean == false) { return 0; } else { if (pa->tamanho > 10 ) { for(int j=0;j < (pa->tamanho/10);j++) { pa->valores = (int *)realloc (pa->valores, j*sizeof(int)); } for(int l=9;l < pa->tamanho; l++); { pa->valores = 0; } } for(int l=0; l < pa->tamanho;l++) { if(pa->valores[l] ==0) { pa->valores[l]=elemento; return 1; } } return 0; } } int ExcluirElemento(TConj* pa,int elemento) { if(pa->boolean ==false) { return 0; } else { for(int j=0; j < pa->tamanho;j++) { if(pa->valores[j]==elemento) { pa->valores=0; return 1; } } return 0; } } void SetElemento (TConj* a, int digi, int pos) { if ( pos <= a->tamanho) { a->valores[pos]= digi; } else { cout << "Essa posição não exite na TAD TConj" << endl; } } int GetElemento(TConj* a, int pos) { int retorno; retorno= a->valores[pos]; return retorno; } int TestaElemento(TConj* a,int digi) { int posicao; for(int i=0;i < a->tamanho;i++) { if(a->valores[i]== digi) { posicao= i; } else { posicao= -1; } } return posicao; } TConj GeraConjunto(int n) { TConj a; Inicializa(&a); for(int i=0; i < a.tamanho;i++) { a.valores[i]=rand(); } return a; } TConj GeraConjuntoSR(int n) { TConj a; Inicializa(&a); for (int i=0; i < a.tamanho; i++) { srand(a.valores[i]); } return a; } TConj Num2Conj(int num) { TConj N2C; char buf[15]; int tam = sprintf(buf, "%d", num); Inicializa(&N2C); for (int i=0; i<tam; i++) { N2C.valores[i]= buf[i]; } return N2C; } int Conj2Num(TConj* a) { int Num=0; for(int i=0; i < a->tamanho;i++) { Num = Num + int(a->valores[i] * pow(10.0,float(a->tamanho - 1) ) ); } return Num; } int Compara(TConj* a,TConj* b) { int comparar=0; if (a->tamanho == b->tamanho) { for (int i=0; i < a->tamanho;i++) { if (a->valores[i] == b->valores[i]) { comparar=1; } else { comparar=0; } } } else { comparar=0; } return comparar; } void Imprime(TConj a) { if(a.boolean == true) { for(int i=0;i < a.tamanho; i++) { cout << "Elemento da " << i << " posicao." << " " << a.valores[i] << " "; } } else { cout << "O TAD não foi inicializado." << endl; } } TConj* Uniao (TConj a,TConj b) { TConj* c; int num,j=0; num= ((a.tamanho) + (b.tamanho)); Inicializa(c); for(int l=0;l < c->tamanho;l++) { if(c->tamanho <= a.tamanho) { c->valores[l]=a.valores[l]; } else { c->valores[l]=b.valores[j]; j++; } } return c; } TConj* Inter (TConj a, TConj b) { TConj* c; int j=0; Inicializa(c); if(a.tamanho > b.tamanho) { for(int l=0;l < a.tamanho;l++) { for(int i=0; i < b.tamanho;i++) { if(a.valores[l]==b.valores[i]) { InserirElemento(c,b.valores[l]); j++; } } } } else { for(int l=0;l < b.tamanho;l++) { for(int i=0; i < a.tamanho;i++) { if(b.valores[l]==a.valores[i]) { InserirElemento(c,b.valores[l]); j++; } } } } return c; } TConj* Subtrair(TConj a,TConj b) { TConj* c; Inicializa(c); if(a.tamanho > b.tamanho) { for(int l=0;l < b.tamanho;l++) { InserirElemento(c,(a.valores[l] - b.valores[l])); } } else { for(int l=0;l < a.tamanho;l++) { InserirElemento(c,(b.valores[l] - a.valores[l])); } } return c; } Main.cpp #include <cstdlib> #include <iostream> #include "TConj.h" using namespace std; int main(int argc, char *argv[]) { TConj a,b,c,d; int elemento, num; Inicializa(a,2); SetElemento(a,2,0); SetElemento(a,5,1); Imprime(a); if (TestaElemento(a,9) == -1) cout << "o elemento 9 não esta presente em a" << endl; elemento = GetElemento(a,1); b = GeraConjuntoSR(8); Imprime(b); c = GeraConjunto(5); SetElemento(c, elemento, 0); Imprime(c); num = Conj2Num(c); d = Num2Conj(num); if (Compara(c,d)) cout << "Os conjunto sao iguais\n " << endl; else cout << "Os conjunto sao diferentes\n " << endl; system("PAUSE"); return EXIT_SUCCESS; } Estou tentando muita dificuldade em trabalhar com ponteiro. Não sei qd é melhor trabalhar com ponteiros e qd é melhor trabalhar com referência. A maioria das funções estão dando erro de referencia indefinida. Será q alguem poderia me ajudar.O escopo das funções eu acho que estão certos. Compartilhar este post Link para o post Compartilhar em outros sites
VictorCacciari 42 Denunciar post Postado Março 24, 2009 Cara, não li teu código...ta bem grandinho! Mas... passagem de parametros por referência só está disponível no C++, e a passagem de parametros por referência é exatamente igual a passagem de um ponteiro. Exemplo: void atribuirValor(int* valor1, int* valor2) { (*valor1) = (*valor2) } void atribuirValor__(int& valor1, int& valor2) { valor1 = valor2; }As duas funções são iguais! O erro 'undefined reference' não se refere a passagem de parametros para as funções. Esse erro aparece quando você usou uma função que não foi declarada. se eu usar sqrt() sem declarar math.h, levarei um 'undefined reference to sqrt(a, B) in line XX' retira aquele 'using namespace std' do arquivo TConj.cpp se você não declarou as funções no namespace std, o compilador não vai achar nunca. outra, se você diz 'using namespace std' você não precisa dizer 'using std::rand' o compilador ja sabe que tudo que você usar está no namespace std. Compartilhar este post Link para o post Compartilhar em outros sites
Herculano 0 Denunciar post Postado Março 25, 2009 Valew eu já havia resolvido o problema com os ponteiros. Mas eu não sabia do namespace std. Só mais um dúvida, eu uso a função rand() para criar números randomicos e a função srand() para criar números randomicos q não repitam ? Compartilhar este post Link para o post Compartilhar em outros sites
VictorCacciari 42 Denunciar post Postado Março 25, 2009 A questão dos números aleatórios... as funções "built-in" da biblioteca padrão, geram apenas números PSEUDO-aletórios. Isso significa que se você precisa de números realmente aleatórios, faça um método você mesmo! srand() é a semente para geração dos números. olha só: srand(1); numero = rand(); printf("%d\n", numero); //agora estamos semeando o gerador dos números com um valor pseudo-aleatório, que é a hora do sistema. //isso faz com que os numeros gerados sejam MAIS aleatórios. srand(time(NULL)); numero = rand(); printf("%d\n", numero); //se voltarmos a semear com o número 1, a aleatoriedade já era... srand(1); numero = rand(); printf("%d\n", numero); note que o primeiro e o último número são iguais, pois o srand foi igual! só é preciso chamar srand UMA vez, no código todo, para números pseudo-aleatórios. os números gerados pela função rand() estão no intervalo [0, RAND_MAX] []'s ps.: srand() vem de "seed random" Compartilhar este post Link para o post Compartilhar em outros sites
_Isis_ 202 Denunciar post Postado Março 27, 2009 Eu faria um pouco diferente, aproveitando que é C++... #include <iostream> #include <vector> #include <algorithm> #include <cstdlib> using namespace std; class TADConjunto { private: vector<int> conjunto; int aleatorio() { return srand(time(0)); } public: TADConjunto(vector<int> tmp) { conjunto.resize(tmp.size); copy(tmp.begin(), tmp.end(), conjunto.begin()); } vector<int> getConjunto() { return conjunto; } void inserirElemento(int elemento) { vector<int>::iterator it; it = find(conjunto.begin(), conjunto.end(), elemento); if (it == conjunto.end()) conjunto.push_back(elemento); } void removerElemento(int elemento) { remove(conjunto.begin(), conjunto.end(), elemento); } void setElementoPosicao(int elemento, int posicao) { if (posicao >= 0) conjunto.insert(elemento, posicao); } int getElementoPosicao(int posicao) { if (posicao >= 0) return conjunto.at(posicao); } void geraConjunto(int tamanho) { if (tamanho > 0) generate_n(conjunto.begin(), tamanho, aleatorio); } bool comparaConjunto(TADConjunto B) { vector<int> diferenca; set_difference(conjunto.begin(), conjunto.end(), B.getConjunto().begin(),B.getConjunto().end(), diferenca); return diferenca.size == 0; } void imprimeConjunto() { for(int i=0; i<conjunto.size;i++) cout << conjunto.at(i) << ' '; } TADConjunto uniao(TADConjunto B) { vector<int> conjunto_uniao; set_union(conjunto.begin(), conjunto.end(), B.getConjunto().begin(), B.getConjunto().end(), conjunto_uniao); TADConjunto novoConjunto(conjunto_uniao); return novoConjunto; } TADConjunto diferenca(TADConjunto B) { vector<int> diferenca; set_difference(conjunto.begin(), conjunto.end(), B.getConjunto().begin(),B.getConjunto().end(), diferenca); TADConjunto novoConjunto (diferenca); return novoConjunto; } TADConjunto intersecao(TADConjunto B) { TADConjunto Cuniao = uniao(B); TADConjunto Cdiferenca = diferenca(B); vector<int> inter; set_difference(Cuniao.getConjunto().begin(), Cuniao.getConjunto().end(), Cdiferenca.getConjunto().begin(), Cdiferenca.getConjunto().end(), inter); TADConjunto novoConjunto (inter); return novoConjunto; } }; Provavelmente faltam algumas coisas. Compartilhar este post Link para o post Compartilhar em outros sites