Consider this,
struct Person {
std::string name;
Person (const std::string& n) : name(n) {}
std::string getName(int, char) const {return name;} // int, char play no role in this
// simple example, but let's suppose that they are needed.
} *Bob = new Person("Bob"), *Frank = new Person("Frank"), *Mark = new Person("Mark"),
*Tom = new Person("Tom"), *Zack = new Person("Zack");
const std::vector<Person*> people = {Bob, Frank, Mark, Tom, Zack};
Because people
is sorted by name, we can carry out a binary search to find the element of people
with a specific name. I want the call for this to look something like
Person* person = binarySearch (people, "Tom",
[](Person* p, int n, char c) {return p->getName(n,c);},
[](const std::string& x, const std::string& y) {return x.compare(y) < 0;}, 5, 'a');
so the template function binarySearch
can be used generically. I got it working with the following:
#include <iostream>
#include <string>
#include <vector>
#include <functional>
struct Person {
std::string name;
Person (const std::string& n) : name(n) {}
std::string getName(int, char) const {return name;} // int, char play no role in this
// simple example, but let's supposes that they are needed.
} *Bob = new Person("Bob"), *Frank = new Person("Frank"), *Mark = new Person("Mark"),
*Tom = new Person("Tom"), *Zack = new Person("Zack");
const std::vector<Person*> people = {Bob, Frank, Mark, Tom, Zack};
template <typename Container, typename Ret>
typename Container::value_type binarySearch (const Container& container, const Ret& value,
std::function<Ret(const typename Container::value_type&, int, char)> f,
std::function<bool(const Ret&, const Ret&)> comp,
typename Container::difference_type low, typename Container::difference_type high,
int n, char c) {
if (low > high)
std::cout << "Error! Not found!\n";
const typename Container::difference_type mid = (low + high) / 2;
const Ret& r = f(container[mid], n, c);
if (r == value)
return container[mid];
if (comp(r, value))
return binarySearch (container, value, f, comp, mid + 1, high, n, c);
return binarySearch (container, value, f, comp, low, mid - 1, n, c);
}
template <typename Container, typename Ret>
typename Container::value_type binarySearch (const Container& container, const Ret& value,
std::function<Ret(const typename Container::value_type&, int, char)> f,
std::function<bool(const Ret&, const Ret&)> comp, int n, char c) {
return binarySearch (container, value, f, comp, 0, container.size() - 1, n, c);
}
int main() {
const Person* person = binarySearch<std::vector<Person*>, std::string>
(people, "Tom", &Person::getName,
[](const std::string& x, const std::string& y) {return x.compare(y) < 0;}, 5, 'a');
std::cout << person->getName(5,'a') << '\n'; // Tom
}
But now for reasons I don't understand, I'm not able to replace the specific arguments int, char
with Args...
. You can go ahead and place Args... args
and args...
where needed in the above code, and it won't compile. What is wrong here? How to carry out this last step in the generalization? Or should the whole method be changed?
This is what I tried:
template <typename Container, typename Ret, typename... Args>
typename Container::value_type binarySearch (const Container& container, const Ret& value,
std::function<Ret(const typename Container::value_type&, Args...)> f,
std::function<bool(const Ret&, const Ret&)> comp,
typename Container::difference_type low, typename Container::difference_type high,
Args... args) {
if (low > high)
std::cout << "Error! Not found!\n";
const typename Container::difference_type mid = (low + high) / 2;
const Ret& r = f(container[mid], args...);
if (r == value)
return container[mid];
if (comp(r, value))
return binarySearch (container, value, f, comp, mid + 1, high, args...);
return binarySearch (container, value, f, comp, low, mid - 1, args...);
}
template <typename Container, typename Ret, typename... Args>
typename Container::value_type binarySearch (const Container& container, const Ret& value,
std::function<Ret(const typename Container::value_type&, Args...)> f,
std::function<bool(const Ret&, const Ret&)> comp, Args... args) {
return binarySearch (container, value, f, comp, 0, container.size() - 1, args...);
}
int main() {
const Person* person = binarySearch<std::vector<Person*>, std::string> (people, "Tom",
&Person::getName,
[](const std::string& x, const std::string& y) {return x.compare(y) < 0;}, 5, 'a');
std::cout << person->getName(5,'a') << '\n';
}
GCC 4.9.2:
[Error] no matching function for call to 'binarySearch(std::vector<Person*>&, const char [4], main()::__lambda0, main()::__lambda1, int, char)'
template argument deduction/substitution failed:
[Note] 'main()::__lambda0' is not derived from 'std::function<std::basic_string<char>(Person* const&, Args ...)>'
Update: Having studied Yakk's solution, I've adapted my solution to the following (using more first principles instead of std::equal_range):
#include <iostream>
#include <iterator>
template <typename Container, typename T, typename Comparator = std::less<T>>
typename Container::value_type binarySearchRandomAccessIterator (const Container& container, T&& value, Comparator&& compare, typename Container::difference_type low, typename Container::difference_type high) {
if (low > high)
{std::cout << "Error! Not found!\n"; return container[high];}
const typename Container::difference_type mid = (low + high) / 2;
const auto& t = compare.function(container[mid]); // Using 'const T& t' does not compile.
if (t == value)
return container[mid];
if (compare.comparator(t, value)) // 't' is less than 'value' according to compare.comparator, so search in the top half.
return binarySearchRandomAccessIterator (container, value, compare, mid + 1, high);
return binarySearchRandomAccessIterator (container, value, compare, low, mid - 1); // i.e. 'value' is less than 't' according to compare.comparator, so search in the bottom half.
}
template <typename ForwardIterator, typename T, typename Comparator = std::less<T>>
typename std::iterator_traits<ForwardIterator>::value_type binarySearchNonRandomAccessIterator (ForwardIterator first, ForwardIterator last, T&& value, Comparator&& compare) {
ForwardIterator it;
typename std::iterator_traits<ForwardIterator>::difference_type count, step;
count = std::distance(first, last);
while (count > 0) { // Binary search using iterators carried out.
it = first;
step = count / 2;
std::advance(it, step); // This is done in O(step) time since ForwardIterator is not a random-access iterator (else it is done in constant time). But the good news is that 'step' becomes half as small with each iteration of this loop.
const auto& t = compare.function(*it); // Using 'const T& t' does not compile.
if (compare.comparator(t, value)) { // 't' is less than 'value' according to compare.comparator, so search in the top half.
first = ++it; // Thus first will move to one past the half-way point, and we search from there.
count -= step + 1; // count is decreased by half plus 1.
}
else // 't' is greater than 'value' according to compare.comparator, so remain in the bottom half.
count = step; // 'count' and 'step' are both decreased by half.
}
if (compare.function(*first) != value)
std::cout << "Error! Not found!\n";
return *first;
}
template <typename Container, typename T, typename Comparator = std::less<T>> // Actually the version below could be used if Container has a random-access iterator. It would be with the same time complexity since std::advance has O(1) time complexity for random-access iterators.
typename std::enable_if<std::is_same<typename std::iterator_traits<typename Container::iterator>::iterator_category, std::random_access_iterator_tag>::value, typename Container::value_type>::type
binarySearch (const Container& container, T&& value, Comparator&& compare = {}) {
std::cout << "Calling binarySearchWithRandomAccessIterator...\n";
return binarySearchRandomAccessIterator (container, value, compare, 0, container.size() - 1);
}
// Overload used if Container does not have a random-access iterator.
template <typename Container, typename T, typename Comparator = std::less<T>>
typename std::enable_if<!std::is_same<typename std::iterator_traits<typename Container::iterator>::iterator_category, std::random_access_iterator_tag>::value, typename Container::value_type>::type
binarySearch (const Container& container, T&& value, Comparator&& compare = {}) {
std::cout << "Calling binarySearchNonRandomAccessIterator...\n";
return binarySearchNonRandomAccessIterator (std::begin(container), std::end(container), value, compare);
}
template <typename Function, typename Comparator>
struct FunctionAndComparator {
Function function;
Comparator comparator;
FunctionAndComparator (Function&& f, Comparator&& c) : function(std::forward<Function>(f)), comparator(std::forward<Comparator>(c)) {}
};
template <typename Function, typename Comparator = std::less<>>
FunctionAndComparator<std::decay_t<Function>, std::decay_t<Comparator>> functionAndComparator (Function&& f, Comparator&& c = {}) {
return {std::forward<Function>(f), std::forward<Comparator>(c)};
}
#include <string>
#include <vector>
#include <list>
struct Person {
std::string name;
Person (const std::string& n) : name(n) {}
std::string getName (int, char) const {return name;} // int, char play no role in this simple example, but let's supposes that they are needed.
} *Bob = new Person("Bob"), *Frank = new Person("Frank"), *Mark = new Person("Mark"), *Tom = new Person("Tom"), *Zack = new Person("Zack");
const std::vector<Person*> peopleVector = {Bob, Frank, Mark, Tom, Zack};
const std::list<Person*> peopleList = {Bob, Frank, Mark, Tom, Zack};
int main() {
Person* tom = binarySearch (peopleVector, "Tom", functionAndComparator([](const Person* p) {return p->getName(5,'a');}, [](const std::string& x, const std::string& y) {return x.compare(y) < 0;}));
if (tom) std::cout << tom->getName(5,'a') << " found.\n";
Person* bob = binarySearch (peopleVector, "Bob", functionAndComparator([](const Person* p) {return p->getName(3,'k');})); // The default comparator, std::less<std::string>, is actually the same as the comparator used above.
if (bob) std::cout << bob->getName(3,'k') << " found.\n";
Person* frank = binarySearch (peopleList, "Frank", functionAndComparator([](const Person* p) {return p->getName(8,'b');}));
if (frank) std::cout << frank->getName(8,'b') << " found.\n";
Person* zack = binarySearch (peopleList, "Zack", functionAndComparator([](const Person* p) {return p->getName(2,'c');}));
if (zack) std::cout << zack->getName(2,'c') << " found.\n";
Person* mark = binarySearch (peopleList, "Mark", functionAndComparator([](const Person* p) {return p->getName(6,'d');}));
if (mark) std::cout << mark->getName(6,'d') << " found.\n";
}