stl sorting question
-
How do I write a function that will help sort my array, by some dynamically specifiable criteria. For example:
class Sortable{ int a; int b; int c; int d; int e; }; void SomeFunction() { std::vector< Sortable> items; // add some items int sortBy = 2; // variable saying I shoul sort by "a" (or "b" or "c", etc) std::stable_sort(items.begin(), items.end(), SortByAorBorC); }
Is it possible to write a function "SortByAorBorC" that takes a paramter (theint sortBy
)??? Right now I'm writing a separate function for each (e.g. "SortByA" "SortByB" and then using a switch statement - it works but it's not very elegant. I can't quite get it going... Many Thanks Warren -
How do I write a function that will help sort my array, by some dynamically specifiable criteria. For example:
class Sortable{ int a; int b; int c; int d; int e; }; void SomeFunction() { std::vector< Sortable> items; // add some items int sortBy = 2; // variable saying I shoul sort by "a" (or "b" or "c", etc) std::stable_sort(items.begin(), items.end(), SortByAorBorC); }
Is it possible to write a function "SortByAorBorC" that takes a paramter (theint sortBy
)??? Right now I'm writing a separate function for each (e.g. "SortByA" "SortByB" and then using a switch statement - it works but it's not very elegant. I can't quite get it going... Many Thanks WarrenYou want to use a function object. For example:
class CMySortFn
{
private:
int m_nSortBy;
public:
CMySortFn(int sortBy) : m_nSortBy(sortBy) { }
// Called by std::sort when comparing items
bool operator()(const Sortable& a, const Sortable& b) const
{
switch (m_nSortBy)
{
case 1:
return a.a < b.a;
case 2:
return a.b < b.b;
etc.
}
}
};std::sort(items.begin(), items.end(), CMySortFn(2));
You could also use a struct as the function object, if you want it even simpler. e.g.:
struct mysortfn
{
int m_nSortBy;
mysortfn(int sortBy) : m_nSortBy(sortBy) { }
bool operator()(const Sortable& a, const Sortable& b) const
{
...
}
};HTH. Have a good weekend.
-
You want to use a function object. For example:
class CMySortFn
{
private:
int m_nSortBy;
public:
CMySortFn(int sortBy) : m_nSortBy(sortBy) { }
// Called by std::sort when comparing items
bool operator()(const Sortable& a, const Sortable& b) const
{
switch (m_nSortBy)
{
case 1:
return a.a < b.a;
case 2:
return a.b < b.b;
etc.
}
}
};std::sort(items.begin(), items.end(), CMySortFn(2));
You could also use a struct as the function object, if you want it even simpler. e.g.:
struct mysortfn
{
int m_nSortBy;
mysortfn(int sortBy) : m_nSortBy(sortBy) { }
bool operator()(const Sortable& a, const Sortable& b) const
{
...
}
};HTH. Have a good weekend.
Robert, Yes! That's exactly what I was looking for, I just didn't know the syntax. Thanks very much! :) Warren