Vector return problem in c++

Asked

Viewed 64 times

1

I’m trying to make a little program to sort vector and I’m using a helper function to do this, but it’s turning me on to this error message.

/media/isaque/dados/exercicios/c/scripts/estrutura de dados com c++/busca_binaria.cpp: In function ‘void ordenar_vetor(int*)’:
/media/isaque/dados/exercicios/c/scripts/estrutura de dados com c++/busca_binaria.cpp:38:7: warning: variable ‘aux’ set but not used [-Wunused-but-set-variable]
   int aux;

this is my script

#include <iostream>
#include <random>
#define TAM 15

int main()
{
  void ordenar_vetor(int *vetor);
  int gerar_aleatorio();

  int valores[TAM];

  for(int c = 0; c < TAM; c++ )
  {
    valores[c] = gerar_aleatorio();
  }

  ordenar_vetor(valores);

  for(int c = 0; c < TAM; c++ )
  {
    std::cout << valores[c] << std::endl;
  }

  return 0;
}



int gerar_aleatorio()
{
  std::random_device m;
  std::uniform_int_distribution<int> gerar(1,100);
  return gerar(m);
}

void ordenar_vetor(int *vetor)
{
  int aux;

  for(int c = 0; c < TAM; c++)
  {
    for(int i = 0; i < TAM; c++)
    {
      if(vetor[c] < vetor[i])
      {
        aux = vetor[i];
        vetor[i] = vetor[c];
        vetor[c] = vetor[i];
      }
    }
  }
}

I can’t identify where I’m going wrong

1 answer

3


There are two errors at the end. You gave a value to aux, but never used it. It’s also increasing c in both ties for, when it should increase i in the second loop. I think you wanted to:

for(int c = 0; c < TAM; c++)
{
    for(int i = 0; i < TAM; i++)
    {
        if(vetor[c] < vetor[i])
        {
            aux = vetor[i];
            vetor[i] = vetor[c];
            vetor[c] = aux;
        }
    }
}

The original code would give the value of vetor[c] to vetor[i], but it wouldn’t change the value of vetor[c], because vetor[i] has already changed. Using aux holds the value of vetor[i] to change the value of vetor[c] correctly.

Also, in the original code, i always has a value 0, then the inner loop never ends.

  • our truth, lack of attention my, but now I’m with another problem, when I leave commented the call of the function "sort vector" it works normal, but when I call the function it just does nothing.

  • Try moving the declaration from ordenar_vetor on top of main. Now you’re declaring inside main.

  • I made a mistake. I just realized there’s a mistake in for loop. In the first you are using c and the second you’re using i, but in the second is increasing c when it should increase i.

  • our is really, thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.