Sorting by Functions in Cilk
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
std::vector<std::string> fruits = {"peach", "banana", "kiwi"};
// We implement a comparison function for string lengths.
auto lenCmp = [](const std::string& a, const std::string& b) {
return a.length() < b.length();
};
// Now we can call std::sort with this custom comparison function
// to sort 'fruits' by name length.
std::sort(fruits.begin(), fruits.end(), lenCmp);
std::cout << "Sorted fruits: ";
for (const auto& fruit : fruits) {
std::cout << fruit << " ";
}
std::cout << std::endl;
// We can use the same technique to sort a vector of
// values that aren't built-in types.
std::vector<Person> people = {
{"Jax", 37},
{"TJ", 25},
{"Alex", 72}
};
// Sort 'people' by age using std::sort.
// Note: if the Person struct is large,
// you may want the vector to contain Person* instead
// and adjust the sorting function accordingly. If in
// doubt, benchmark!
std::sort(people.begin(), people.end(),
[](const Person& a, const Person& b) {
return a.age < b.age;
});
std::cout << "Sorted people: ";
for (const auto& person : people) {
std::cout << person.name << "(" << person.age << ") ";
}
std::cout << std::endl;
return 0;
}
This Cilk code demonstrates custom sorting using comparison functions, similar to the original example. Here’s an explanation of the key differences and adaptations:
We use C++ syntax and standard library components, as Cilk is an extension of C++.
Instead of
slices.SortFunc
, we usestd::sort
from the C++ Standard Library, which allows custom comparison functions.We define the comparison functions as lambda expressions, which is idiomatic in C++.
For string comparisons, we use the
<
operator directly on string lengths, which is equivalent to thecmp.Compare
function in the original example.We use
std::vector
instead of slices, as this is the standard resizable array type in C++.To print the sorted results, we use C++ streams (
std::cout
) and range-based for loops, which is more idiomatic in C++.The
Person
struct is defined similarly, but we use the C++struct
keyword and std::string for the name field.
This code maintains the structure and explanation provided in the original example while adapting it to Cilk (C++) syntax and idioms. It demonstrates how to perform custom sorting on both built-in types (strings) and user-defined types (Person struct) using comparison functions.