BAN: Implement next() and prev() for iterators and use them in sorts

This commit is contained in:
Bananymous 2023-12-07 19:28:05 +02:00
parent 1aef0f5f0e
commit 9f5bdde29d
2 changed files with 33 additions and 2 deletions

View File

@ -1,10 +1,41 @@
#pragma once #pragma once
#include <BAN/Assert.h> #include <BAN/Assert.h>
#include <BAN/Traits.h>
namespace BAN namespace BAN
{ {
template<typename It>
It next(It it, size_t count)
{
for (size_t i = 0; i < count; i++)
++it;
return it;
}
template<typename It>
requires requires(It it, size_t n) { requires is_same_v<decltype(it + n), It>; }
It next(It it, size_t count)
{
return it + count;
}
template<typename It>
It prev(It it, size_t count)
{
for (size_t i = 0; i < count; i++)
--it;
return it;
}
template<typename It>
requires requires(It it, size_t n) { requires is_same_v<decltype(it - n), It>; }
It prev(It it, size_t count)
{
return it - count;
}
template<typename T, typename Container, bool CONST> template<typename T, typename Container, bool CONST>
class IteratorSimpleGeneral class IteratorSimpleGeneral
{ {

View File

@ -10,7 +10,7 @@ namespace BAN
void sort_exchange(It begin, It end, Comp comp = {}) void sort_exchange(It begin, It end, Comp comp = {})
{ {
for (It lhs = begin; lhs != end; ++lhs) for (It lhs = begin; lhs != end; ++lhs)
for (It rhs = lhs; ++rhs != end;) for (It rhs = next(lhs, 1); rhs != end; ++rhs)
if (!comp(*lhs, *rhs)) if (!comp(*lhs, *rhs))
swap(*lhs, *rhs); swap(*lhs, *rhs);
} }
@ -21,7 +21,7 @@ namespace BAN
template<typename It, typename Comp> template<typename It, typename Comp>
It sort_quick_partition(It begin, It end, Comp comp) It sort_quick_partition(It begin, It end, Comp comp)
{ {
It pivot = end; --pivot; It pivot = prev(end, 1);
It it1 = begin; It it1 = begin;
for (It it2 = begin; it2 != pivot; ++it2) for (It it2 = begin; it2 != pivot; ++it2)