Why do some STL algorithms provide an additional '_if'
function instead of overloading it?
// example:
find(beg, end, val);
find_if(beg, end, pred);
Couldn't they just have overloaded those algorithms instead of making additional _if
functions?
By returning the end of an input sequence, the algorithms indicate failure. For instance, find(begin, end, x) returns end if it can not find x.
STL provides a range of data structures that are very useful in various scenarios. A lot of data structures are based on real-life applications. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized.
std::remove, std::remove_if. Removes all elements satisfying specific criteria from the range [first, last) and returns a past-the-end iterator for the new end of the range. 1) Removes all elements that are equal to value , using operator== to compare them.
The string class is not part of the STL, but has implemented many STL features. string can be treated as a STL container of char .
It isn't clear how overload resolution would work generically. What if, say, the container contains predicates?
struct pred
{
bool operator()(const pred&) const;
friend bool operator==(const pred&,const pred&);
};
std::vector<pred> v;
pred p;
std::find(v.begin(), v.end(), p); // what should happen here?
This potential ambiguity is avoided by having functions with different names, each name expressing the intent more clearly.
Note that this is a simplification: there is no requirement in std::find
that the reference object be of the same type as that value_type
of the container, just that they be comparable for equality. The requirements for the predicate in std::find_if
are similarly generic. Both these functions are extremely generic, which means an ambiguity could arise more easily than in the example given. For example,
struct foo {};
struct pred
{
bool operator()(const foo&) const;
};
bool operator==(const foo&, const pred&);
int main()
{
std::vector<foo> v;
pred p;
std::find(v.begin(), v.end(), p); // What should this do?
std::find_if(v.begin(), v.end(), p); // Here, it is clear.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With