The std::unique algorithm keeps only unique elements in consecutive groups of elements. Meanwhile, sometimes it is useful to know how many specific elements were in the initial container. Like to make a convolution with number of elements and their amounts.
Is there such an algorithm in STL or some straightforward way to do this not considering writing the whole code from scratch (which is easy, but I want to reuse existing solutions as much as possible) and avoiding extra containers like std::unordered_map, etc.? The key is to have an easy and straightforward solution like std::equal.
It could seem like std::unique with an additional iterators to write amounts or making std::unique working with std::pair where the first will store the value and the second its amount.
For example
For container
[1, 1, 2, 2, 1, 1]
as the result I’d like to have either two containers [1,2,1] and [2,2,2] where the first keep values and second one keeps their amounts in consecutive groups (in this case [1,2] and [4,2] could be an option, but this is slightly different topic) or one container like [{1,2}, {2,2}, {1,2}].
>Solution :
With the help of <ranges>, you may want to use views::chunk_by
auto l = {1, 1, 2, 2, 1, 1};
auto r = l | std::views::chunk_by(std::ranges::equal_to{})
| std::views::transform([](auto chunk) {
return std::pair{chunk.front(), chunk.size()};
});
If you need to collect numbers and amounts separately, you can use views::keys/views::values
auto numbers = r | std::views::keys;
auto amounts = r | std::views::values;