Suppose I have the following snippets:
int compareFoo(std::string** a, std::string** b) {
return (**a).compare(**b);
}
int main() {
std::string** foo = new std::string*[3];
foo[0] = new std::string("a");
foo[1] = new std::string("c");
foo[2] = new std::string("b");
sort(foo,foo+3,compareFoo);
for (int i = 0; i < 3; i++) {
std::cout << *foo[i] << std::endl; // print acb
}
}
If I’d left out the third parameter(compare) for sort, it’d have given me the sorted 3 strings in terms of their memory addresses, that’s not how I intended it. But how do I parameterize the compareFoo function so that it won’t compare the memory addresses.
void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
The description of Sort on cplusplus.com is quite vague and the given example is simple. Since it takes an Iterator, does it mean that i only work with stand containers? Thank you
The comparison function takes two items to compare and returns true if the first one is less than the second one. In your case, it would work like this: