stack insertion vector returning all zero

0

Now, I posted the algorithm for this address below here because I had problems with unpacking and removing was solved until then. Deploying Dynamic Stack

But as I was reviewing the code and therefore leaving them better I decided to put a for so that the user is not typing 1 in the menu to enter the numbers, then he would do the insertion according to the size of the vector:

So I did this below:

   if(op == 1)
    {
     for(i=0;i<=9;i++)
     {
      std::cout << "\n\tINSIRA NUMERO "<<i+1<<" NA PILHA: ";
       pilha *novo = new pilha();
       std::cin >> novo->num[i];
       novo->prox = topo;
       topo = novo;
      std::cout << "\n\tNUMERO "<<novo->num[i]<<" INSERIDO COM SUCESSO!!!";
     }
    }

But when I type 2 it returns all zero. What did I do wrong?

   if(op == 2)
    {
     i++; 
     if(topo == NULL)std::cout << "\n\tPILHA VAZIA!!!";
     else
      {
       std::cout << "\n\tPILHA COMPLETA: ";
       aux = topo;
       while(aux != NULL)
       {
        std::cout << aux->num[i] << " ";
        aux = aux->prox;
       }
      }
    }
    
asked by anonymous 19.01.2018 / 22:14

1 answer

1

If you want to add multiple elements in a stack at the cost of a for , you do not need to transform each element of the stack into a vector, and you can keep the old structure you had:

struct pilha {
    int num; //sem ser vetor
    pilha *prox;
};

Changing the insertion to:

for(i=0; i<=9; i++) {
    std::cout << "\n\tINSIRA NUMERO "<<i+1<<" NA PILHA: ";
    pilha *novo = new pilha();
    std::cin >> novo->num; //sem o ->num[i]
    novo->prox = topo;
    topo = novo;
    std::cout << "\n\tNUMERO "<<novo->num<<" INSERIDO COM SUCESSO!!!";//tambem sem num[i]
}

The for itself already makes all the inserts you want, depending on the number of times you set it to execute.

The reading would have to be set to:

if(op == 2) {
    //sem i++;
    if(topo == NULL)std::cout << "\n\tPILHA VAZIA!!!";
    else {
        std::cout << "\n\tPILHA COMPLETA: ";
        aux = topo;
        while(aux != NULL) {
            std::cout << aux->num << " "; //sem ->num[i]
            aux = aux->prox;
        }
    }
}

The problem I had is that every element in the stack had 10 numbers, but you were only filling one and leaving the other 9 empty. Analyzing the for you had:

for(i=0;i<=9;i++)
 {
   ...
   pilha *novo = new pilha(); //criar um novo elemento para a pilha
   std::cin >> novo->num[i]; //preencher um numero apenas numa posição do vetor
   ...
 }

Notice how you fill in only one position because at each iteration you create a new pilha .

    
20.01.2018 / 00:02