I got a strange error while compiling this code. Its the same as in the book im studying from, but it seems it gets confused somewhere, because my output is off, ages and names got mixed eg( darko 4, zdendk 3, matija 2, draga(dont know where the "n" is gone) 1) and it says invalid pointer. Help me to understand why this is happening.
#include <iostream>
#include <math.h>
#include <cstdlib>
//#include "Tablica.h"
using namespace std;
/*
*
*/
struct Person {
string name;
int age;
};
int compare (const void* a, const void* b){
const Person* p1 = static_cast<const Person*>(a);
const Person* p2 = static_cast<const Person*>(b);
if(p1->age != p2->age)
return p2->age - p1->age;
return p1->name.compare(p2->name);
}
int main(int argc, char** argv) {
Person people[]{{"darko", 1},{"zdendka", 2},{"matija", 3},{"dragan", 4}};
int numP = sizeof(people) / sizeof(Person);
qsort(people, numP, sizeof(Person), compare);
for(Person x:people){
cout<< x.name <<" "<<x.age<<endl;
}
return 0;
}
qsortdoesn't work properly withstd::string, trystd::sortinstead.qsort()function uses byte-by-byte copying to move data. That may not work properly for strings.string,iostreams), C++11 (range basedforand initializer lists) and C functions (qsort). Use C++ rich library of functions, classes and templates. Sostd::arrayorstd::vectorrather than the C-array you are using andstd::sortinstead ofqsortand you should be pretty much there.