From 518fce5ef5fe313ea4efb6a1e3c29e1676a8759a Mon Sep 17 00:00:00 2001 From: Patrick Date: Mon, 29 Jul 2024 16:31:32 +0200 Subject: [PATCH] fixed all insert() variants --- include/const_vector.hpp | 50 +++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/include/const_vector.hpp b/include/const_vector.hpp index e0c41c5..3fecbcb 100644 --- a/include/const_vector.hpp +++ b/include/const_vector.hpp @@ -396,41 +396,49 @@ namespace cc { template constexpr const_vector::iterator const_vector::insert(const_vector::const_iterator pos, const T &value) { - if (_size == N) throw std::exception(); + if (_size == N) throw std::length_error("No space left in vector"); - ptrdiff_t i = pos - _arr; - std::move(_arr + i, _arr + _size, _arr + i + 1); - _arr[i] = value; + auto it = const_cast(pos); + if (pos != end()) { + std::move_backward(it, end(), end() + 1); + } + *it = value; ++_size; - return pos; + + return it; } template constexpr const_vector::iterator const_vector::insert(const_vector::const_iterator pos, T &&value) { - if (_size == N) throw std::exception(); + if (_size == N) throw std::length_error("No space left in vector"); - ptrdiff_t i = pos - _arr; - std::move(_arr + i, _arr + _size, _arr + i + 1); - _arr[i] = std::move(value); + auto it = const_cast(pos); + if (pos != end()) { + std::move_backward(it, end(), end() + 1); + } + *it = std::forward(value); ++_size; - return pos; + + return it; } template constexpr const_vector::iterator const_vector::insert(const_vector::const_iterator pos, const_vector::size_type count, const T &value) { - if (count == 0) return pos; - if (_size + count >= N) throw std::exception(); + auto it = const_cast(pos); + + if (count == 0) return it; + if (_size + count > N) throw std::length_error("Not enough space left in vector for " + std::to_string(count) + " elements"); - std::move(pos, _arr + _size, pos + count); - std::fill(pos, pos + count, value); + std::move_backward(it, end(), end() + count); + std::fill(it, it + count, value); _size += count; - return pos; + return it; } template @@ -439,16 +447,16 @@ namespace cc { const_vector::insert(const_vector::const_iterator pos, InputIt first, InputIt last) { auto count = std::distance(first, last); + auto it = const_cast(pos); - if (first == last) return pos; - if (_size + count >= N) throw std::exception(); + if (first == last) return it; + if (_size + count > N) throw std::length_error("Not enough space left in vector for " + std::to_string(count) + " elements"); - - std::move(pos, _arr + _size, pos + count); - std::copy(first, last, pos); + std::move_backward(it, end(), end() + count); + std::copy(first, last, it); _size += count; - return pos; + return it; } template