hi, i've been having trouble with relocating a value in a vector when using pointers as passage in the 'exchange' function.
in this exercise i need to read n values for a vector, then pass a new value to the function as a pointer, and order it inside the vector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
using namespace std;
void troca (int*, int*, int);
int main () {
int n, i, tamanho, vet[10], *ptrvalor, valor;
cin >> n;
for (i=0;i<n;i++) {
cin >> vet[i];
}
cin >> valor;
ptrvalor = &valor;
tamanho = sizeof(vet)/sizeof(int);
troca (vet, ptrvalor, tamanho);
for (int j=0;j<n+1;j++) {
cout << vet[j] << "";
} cout << endl;
return 0;
}
void troca (int* vet, int* ptrvalor, int tamanho) {
int aux;
for (int i=(tamanho-1); i>0; i--) {
if (*ptrvalor > vet[i]) {
aux = vet[i];
vet[i] = *ptrvalor;
vet[i+1] = aux;
}
}
}
|
i don't understand what i'm doing wrong in the passage, as the code compiles.
if i input, say, 'n' as 5, then fill the vector with '1,2,3,5,6' and the value as '4';
it should output: '1,2,3,4,5,6'
but the result i get is: '1,2,4,5,6,4'
please help me find my flawed logic, or point me to a thread where a similar problem has been solved, as i couldn't find any. thanks.