York wrote:
Lets say I have the following structure
struct test_struct
{
int some_number;
char first_name[10]
}
test_struct s_table[100]
In short a table within a table with a number, I would like to know if
there are any standard sorting algorithms implemented in c/c++ to sort
s_table in an alphabetical order based on first_name
In C, you would probably want to use the qsort function. C is off-topic
here, so I'll just tell you to look up "qsort" in your C textbook or on the
web.
In C++, you'd do something like this:
#include <algorithm>
#include <cstddef>
#include <cstring>
#include <iostream>
#include <iterator>
#include <ostream>
namespace
{
std::size_t const NAME_LENGTH(9);
struct test_struct
{
int some_number;
char first_name[NAME_LENGTH + 1];
};
bool order_by_first_name (test_struct const &ts1,
test_struct const &ts2)
{
return std::strcmp(ts1.first_name, ts2.first_name) < 0;
}
std::ostream &operator<< (std::ostream &os, test_struct const &ts)
{
return os << ts.some_number << ": " << ts.first_name;
}
}
int main()
{
std::size_t const ARRAY_SIZE(3);
test_struct s_table[ARRAY_SIZE] = { { 1, "Tom" },
{ 2, "Dick" },
{ 3, "Harry" } };
typedef std::ostream_iterator<test_struct> test_struct_writer;
test_struct_writer ts_writer(std::cout, "\n");
std::cout << "Before sorting:\n";
std::copy(s_table, s_table + ARRAY_SIZE, ts_writer);
std::sort(s_table, s_table + ARRAY_SIZE, order_by_first_name);
std::cout << "\nAfter sorting:\n";
std::copy(s_table, s_table + ARRAY_SIZE, ts_writer);
}
--
Russell Hanneken
rg********@pobox.com
Remove the 'g' from my address to send me mail.