0
std::list<int> ll{1,2,3,4,5,7,9};
auto end = ll.begin();
std::advance(end , 5);
std::cout << "end element: " << *end << std::endl; (output as '7')
auto middle = std::partition(std::begin(ll), end, [](const auto& item){ return item % 2; });
for(int fi : ll) std::cout << fi << ' ';

From the above snippet I expect : 1 7 3 5 4 2 9(for instance), however I get 1 5 3 4 2 7 9.

std::partition in STL has been implemented to ignore the last element? to work around this quicksort example program in cppreference is also unnecessarily complicated.

checked the STL GCC implementation: Its purposely left out maybe "__pred(*__last)" could be UB for one past last iterator (std::end) However in my example above it's not.

below code yields me what i want though its not complete.

template<typename BidirectionalIterator, typename Predicate>
BidirectionalIterator my_partition(BidirectionalIterator __first, BidirectionalIterator __last,
                                        Predicate __pred){

    while (true)
    {
        while (true)
            if (__first == __last)
                return __first;
            else if (__pred(*__first))
                ++__first;
            else
                break;
        /*--__last;*/
        while (true)
            if (__first == __last)
                return __first;
            else if (!bool(__pred(*__last)))
                --__last;
            else
                break;
        std::iter_swap(__first, __last);
        ++__first;
    }
}
  • 2
    If you read the documentation it's clear `[first, last)` it means first included, and end excluded. – foragerDev Jul 11 '21 at 12:12
  • 2
    You are *meant* to pass one-past-end iterators. All the standard algorithms operate in terms of half-open ranges. begin is inclusive, while end is logically *after* the last element in the range. Even the core language was designed to support this idiom when the iterators are pointers. – StoryTeller - Unslander Monica Jul 11 '21 at 12:12
  • And further, Handling the iterators, where Iterators point to is the programmer's responsibility, STL does not take any responsibility for that. – foragerDev Jul 11 '21 at 12:14

0 Answers0