How does the STL algorithm work regardless of the type of Iterator?

How does the STL algorithm work regardless of the type of Iterator?

+3
source share
6 answers

Indeed, they just work. They use some fairly simple template properties, sometimes called static polymorphism. If you are familiar with the term, it is essentially a duck shape. (If it looks like a duck and it dips like a duck, it must be a duck)

The trick is simple. Here is a very simple example:

template <typename T>
void say_hello(const T& t) {
  t.hello();
}

say_hello , . - "promises" , . , , - , . , , hello. , , hello.

STL . std::for_each:

template <typename iter_type, typename func_type>
void for_each(iter_type first, iter_type last, func_type f){
  for (iter_type cur = first; cur != last; ++cur) {
    f(*cur);
  }
}

, , ; iter_type pre-increment ++ -. , ! =, * -dereference.

func_type -, , , iter_type. for_each , , . iter_type , . , " , ". , , .

+15

STL - , , .

( , ..).

STL, ( ++, ), . , , ( ).

+4

STL , .

++ .

+3

STL , .

+1

/ STL ​​. , Generic Algorithms, STL.

:

  • , , find, count, for_each,...
  • , , , , , , ,...
  • , , , , nth_element.

Some non-general algorithms can be divided into 2 stages, the general part of the STL and the part that depends on the container. Thus, in order to destroy all values ​​exceeding 7 in the vector, we can do remove_if (the common part that only sorts the elements), followed by the erase (non-negative part that destroys the value).

0
source

Source: https://habr.com/ru/post/1710907/


All Articles