I’m not sure exactly what the following class does that we have for a class example. In the following code, what does the operator() do in this case? I don’t quite get the *(begin + first) and pretty much the whole return expression as what is being evaluated. Any help would be great. Thanks!
// IndexCompare.h - interface for IndexCompare class template
#ifndef _INDEXCOMPARE_H_
#define _INDEXCOMPARE_H_
#pragma once
template <class random_iterator>
class IndexCompare {
public:
IndexCompare(random_iterator begin, random_iterator end)
: begin(begin), end(end) {}
~IndexCompare() {}
bool operator() (unsigned int first, unsigned int second) {
return (*(begin + first) < *(begin + second));
}
private:
random_iterator begin;
random_iterator end;
};
#endif
If you’re asking what
operator ()does, it allows you to call the object like a function. See this article for an example.If you’re asking what the function in your example is doing, it’s comparing the values of two elements specified by the indices passed to the function.
begin + firstrefers to the element at indexfirststarting from the iteratorbegin, similarlybegin + second.*(begin + first)gets the value at that location.You can use this class with any STL container (that supports random access) by passing in a pair of iterators. For example, you could use it with a vector like this:
Now calling
compare(2, 5)for example would compare the values ofvec[2]andvec[5].