diff options
author | Jacques Lucke <jacques@blender.org> | 2022-02-24 16:45:41 +0300 |
---|---|---|
committer | Jacques Lucke <jacques@blender.org> | 2022-02-24 16:50:13 +0300 |
commit | 9be720d85efb307ad37b73f0f5fffd95629c7e20 (patch) | |
tree | 8b0c0f074c9f6616ff2b79992974177b2d4215ef /source/blender/blenlib/BLI_array.hh | |
parent | 7cab7eb3d6cd929f5c354416b4baa6c608f08d82 (diff) |
BLI: support accessing nth last element in Array/Span/Vector
This often helps to make the intend of code more clear compared
to computing the index manually in the caller.
Diffstat (limited to 'source/blender/blenlib/BLI_array.hh')
-rw-r--r-- | source/blender/blenlib/BLI_array.hh | 18 |
1 files changed, 10 insertions, 8 deletions
diff --git a/source/blender/blenlib/BLI_array.hh b/source/blender/blenlib/BLI_array.hh index a580f12851e..91dfc81ae27 100644 --- a/source/blender/blenlib/BLI_array.hh +++ b/source/blender/blenlib/BLI_array.hh @@ -278,18 +278,20 @@ class Array { } /** - * Return a reference to the last element in the array. - * This invokes undefined behavior when the array is empty. + * Return a reference to the nth last element. + * This invokes undefined behavior when the array is too short. */ - const T &last() const + const T &last(const int64_t n = 0) const { - BLI_assert(size_ > 0); - return *(data_ + size_ - 1); + BLI_assert(n >= 0); + BLI_assert(n < size_); + return *(data_ + size_ - 1 - n); } - T &last() + T &last(const int64_t n = 0) { - BLI_assert(size_ > 0); - return *(data_ + size_ - 1); + BLI_assert(n >= 0); + BLI_assert(n < size_); + return *(data_ + size_ - 1 - n); } /** |