1) You shall not use qsort for non-POD types. It wreaks their integrity. Also there is a great chance that you forgot to initialize n_teams. Is there any reason to use C function qsort instead of C++ std::sort?
2) Any reason to explicitely place struct before typename in C++?
Thanks for the reply.
What do you mean by non-POD types (excuse me, I am a beginner)?
I did initialize n_teams in the main() function.
Our teacher told us we could use qsort to sort an array of structs. I still did not get the reason not to use qsort in this case.
How could I use C++ std::sort in this case, that is, if I had to sort struct team_info teams[] by their "points"?
Is there any problem if I explicitly place struct before typename in C++?
Thanks in advance. :)
Is there any problem if I explicitly place struct before typename in C++?
No, but there is no need to do so in C++. Usually this is the first sign that person does not actually learning C++, but C with classes instead.
How could I use C++ std::sort in this case, that is, if I had to sort struct team_info teams[] by their "points"?
Same way like you would use qsort: create comparison function and pass it to std::sort. But without type erasure, unsafe cast and with compiler error checking:
#include <algorithm>
#include <iostream>
#include <string>
struct team_info
{
std::string name;
int played, won, drawn, lost, points, goals_for, goals_against, diff;
};
struct tourney
{
std::string tourney_name;
int n_teams;
int n_games;
struct game
{
std::string home;
int h_score;
std::string away;
int a_score;
}g[1000];
team_info team[30];
} t;
bool compare_points_less(const team_info& lhs, const team_info& rhs)
{
return lhs.points < rhs.points;
}
int main()
{
constint teams = 5;
t.n_teams = teams;
//initialize teams
int scores[teams] = { 1, 8, 3, 5, 0};
for(int i = 0; i < teams; ++i) {
t.team[i].points = scores[i];
std::cout << t.team[i].points << ' ';
}
std::cout << '\n';
//sort
std::sort(t.team, t.team + t.n_teams, compare_points_less);
//display sorted
for(int i = 0; i < t.n_teams; ++i) {
std::cout << t.team[i].points << ' ';
}
}
Our teacher told us we could use qsort to sort an array of structs.
Only trivial types like int. double, etc. string is not a trivial type and should not be sorted that way. Often strings contain a so-called small string optimisation which required them to contain pointer to itself. If you do a bitwise swap, those pointers start pointing to other object, completely breaking class and making it unusable and dangerous.