Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some STL algorithms provide an additional '_if' function instead of overloading? [duplicate]

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?

like image 516
alberto Avatar asked May 19 '15 22:05

alberto


People also ask

How does an STL algorithm usually indicate not found or failure?

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.

What is the advantage of STL in C++?

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.

What does std:: remove do?

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.

Is string part of STL?

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 .


1 Answers

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.
}
like image 55
juanchopanza Avatar answered Nov 15 '22 17:11

juanchopanza