You already have your C-style solution.
I want to give you a simple C++ - style alternative.
Here is the code:
#include <iostream>
#include <string>
#include <map>
int main()
{
static const int runs_size = 15;
struct team
{
int runs[runs_size];
std::string name;
} ind, pak, aus;
memset(&ind, 0, sizeof(ind));
memset(&pak, 0, sizeof(pak));
memset(&aus, 0, sizeof(aus));
ind.name = "India";
pak.name = "Pakistan";
aus.name = "Australia";
ind.runs[0] = 10; ind.runs[5] = 20; ind.runs[10] = 25;
pak.runs[1] = 17; pak.runs[2] = 18; pak.runs[12] = 23;
aus.runs[4] = 10; aus.runs[5] = 19; aus.runs[6] = 24;
typedef std::multimap<int, const team*, std::greater<int> > mmap_runs_teams_t;
typedef std::pair<int, const team*> mmap_pair_t;
mmap_runs_teams_t mmap_runs_teams;
for (int i = 0; i < runs_size; i++)
{
mmap_runs_teams.insert(mmap_pair_t(ind.runs[i], &ind));
mmap_runs_teams.insert(mmap_pair_t(pak.runs[i], &pak));
mmap_runs_teams.insert(mmap_pair_t(aus.runs[i], &aus));
}
std::cout << "Best runs: " << std::endl;
for (mmap_runs_teams_t::iterator it = mmap_runs_teams.begin(); it != mmap_runs_teams.end(); it++)
{
std::cout << "\nRun: " << it->first << "\tTeam: " << it->second->name;
}
std::cin.get();
return 0;
}
The output of this program:
Best runs:
Run: 25 Team: India
Run: 24 Team: Australia
Run: 23 Team: Pakistan
Run: 20 Team: India
Run: 19 Team: Australia
Run: 18 Team: Pakistan
Run: 17 Team: Pakistan
Run: 10 Team: India
Run: 10 Team: Australia
........... all zero runs to the end..........
From the code above you can see that the actual solution is
less then 10 lines of code! :)
This is possible with the
Standard C++ Library. I used
std::multimap[
^] as a container.
Intentionally I will not explain how this solution works.
As an exercise, you can check out the documentation for
std::multimap
.
This way you can understand how this code works.
If you have some questions after reading the documentation, please feel free to ask here. :)