Container version of C ++ sort

I read the Stroustrup C ++ blog ( http://isocpp.org/blog/2014/12/myths-3 ) when I found the code snippet:

void do_my_sort(vector<double>& v)
{
  sort(v,[](double x, double y) { return x>y; });  // sort v in decreasing order
}

int main()
{
  vector<double> vd;
  // ... fill vd ...
  do_my_sort(v);
  // ...
} 

Note that it sortdoes not use the traditional sort(v.begin(), v.end(), ...)one that Stroustrup explains:

I used the container version sort()to avoid explicit iterators.

However, I tried the same code in my C ++ 11 compiler, but could not compile it. I also tried the same thing in the C ++ 14 compiler using ideone, but it also does not compile, saying that there is no corresponding call to sort.

Why is this?

In addition, the following is mentioned in Straustupat:

I could go further and use the C ++ 14 comparison object:

sort(v,greater<>()); // sort v in decreasing order

great<>() sort ++ 11. , ++ 14?

+4
3

, . , . :

template <class Container, class Comp>
void sort (Container& cont, Comp comp) {
    using std::begin;
    using std::end;
    std::sort(begin(cont), end(cont), comp);
}

, boost:: sort, .

+10

great<>() ++ 11. , ++ 14?

++ 14 operator() . Function Objects , void .

template< class T = void >
struct greater
{
    constexpr bool operator()(const T &lhs, const T &rhs) const;
};

template<>
struct greater<void>
{
    template< class T, class U>
    constexpr auto operator()( T&& lhs, U&& rhs ) const
      -> decltype(std::forward<T>(lhs) > std::forward<U>(rhs));
};
+4

Perhaps it uses Boost sorting rather than standard sorting, as you would expect. Therefore, he boost::sort, not std::sort.

+1
source

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


All Articles