Hi.
I'm trying to understand how pointers work. I have an algorithms implemented in two ways: one using pointers, the other not so much. The thing is, the second implementation works, the first doesn't and I'm not sure why.
Here's my main (IN_FILE, N_DATA and E_GOOD are globally defined variables: name of an input-file, 1000, and the exit code):
Here's the pointer based sorting:Code:int main(const int argc, const char *argv){ ifstream fin(IN_FILE); vector< Supplier >* supps = new vector< Supplier > (N_DATA); for(int i = 0; i < N_DATA; ++i) fin >> supps->at(i).companyID >> supps->at(i).price; printSuppliers( &selectionSort(*supps), 2); supps = sort(supps); cout << "<--------------------------->" << endl; printSuppliers(supps, 2); return E_GOOD; }
and the non-pointer based:Code:vector< Supplier > * sort(vector< Supplier > *v){ int i, j, min; for (i = 0; i < v->size() - 1; i++){ min = i; for (j = i+1; j < v->size(); j++){ if (v->at(i).price < v->at(min).price){ min = j; } } swap(v->at(i), v->at(min)); } return v; }
here's the printing function:Code:vector<Supplier> selectionSort(vector<Supplier> a){ int i, j, min; for (i = 0; i < a.size() - 1; i++){ min = i; for (j = i+1; j < a.size(); j++){ if (a[j].price < a[min].price){ min = j; } } swap(a[i], a[min]); } return a; }
My first output (from the dereferenced sorting) is in correct order, but the second output is unsorted:Code:void printSuppliers(const vector< Supplier > *v, int n){ for(int i = 0; i < n; i++){ cout << "Supplier: " << i << endl << "\tID: " << v->at(i).companyID << endl << "\tPrice: " << v->at(i).price << endl << endl ; } }
Anyone care to help me understand why this is happening?Code:Supplier: 0 ID: C956 Price: 828 Supplier: 1 ID: C38 Price: 893 <---------------------------> Supplier: 0 ID: C0 Price: 1869 Supplier: 1 ID: C1 Price: 1728



LinkBack URL
About LinkBacks



