You need iterators into your array and some sorting criterion. Let's start with the iterators:
You will need a begin iterator and an end iterator. The begin iterator needs to point to the first element, the end iterator needs to point behind the last element. Pointers are perfect iterators. An array is implicitly convertible into a pointer to its first element, so you have a begin iterator. Add the number of elements in the array to it and you have an end iterator. The number of elements in the array can be obtained by dividing the size (number of bytes) of the array by the size of a single element. Putting it all together:
foo array[10];
const std::size_t array_size = sizeof(array)/sizeof(array[0]);
const int* array_begin = array; // implicit conversion
const int* array_end = begin + array_size;
Now you need something for the algorithm to decide which of two given objects of your class is the smaller one. An easy way to do this would be by overloading operator<
for your class:
bool operator<(const foo& lhs, const foo& rhs)
{
// compares using foo's bar
return lhs.get_bar() < rhs.get_bar();
}
Now you can sort your array:
std::stable_sort( array_begin, array_end );
If the sorting criterion isn't as fix (say, sometimes you want to sort based on foo
's bar
data, sometimes based on its wrgly
data), you can pass different sorting criteria to the sort algorithm as an optional third parameter. Sorting criteria should be function-like entities. That can be functions or function objects. The latter provide inlining, which is why they are usually better. Here's both:
bool compare_by_bar(const food& lhs, const foo& rhs)
{
return lhs.get_bar() < rhs.get_bar();
}
struct wrgly_comparator {
bool operator()(const food& lhs, const foo& rhs) const
{
return lhs.get_wrgly() < rhs.get_wrgly();
}
};
This is how you use them:
std::stable_sort( array_begin, array_end, compare_by_bar );
wrgly_comparator wc;
std::stable_sort( array_begin, array_end, wc );
You can also create the comparator on the fly:
std::stable_sort( array_begin, array_end, wrgly_comparator() );
Edit: Here's a few more hints based on your expanded question:
sortContainer * sortList = new sortContiner [length];
will create a dynamic array on the heap. In C++, there is no garbage collection and you are responsible for cleaning up on the heap after yourself (in this case by invoking delete[] sortList;
). This is notoriously hard to do for novices and error-prone even for seasoned programmers. There's a very good chance that what you want is an automatic array: sortContainer sortList[length];
on the stack.
The identifier sortContainer
tells me that the thing is a container. However, it's the type of the items to be put into the container. Be more careful by picking identifiers. Proper naming goes a long way towards readable and maintainable code.