Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an algorithm in STL like std::unique which stores the amount of equal objects?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()};
             });

Demo

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;

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading