mardi 17 avril 2018

Generating a dynamic size dynamic container with STL algorithms

I would like to create a container of elements of unknown size using STL algorithm header. I want to avoid writing my own loop. The motivation behind this is writing expressive and safe code, as argued by Kate Gregory in Beautiful C++ on Pluralsight.

My approach so far is limited to containers of known size. ( I'm talking about dynamic containers).

Example:

int expected_container_size = 10;

std::vector<int> dynamic_container;
dynamic_container.reserve(expected_container_size);

auto example_iota_generator = [n = 0]()mutable{return ++n; };

std::generate_n(std::back_inserter(dynamic_container), expected_container_size, example_iota_generator);

To repeat the question:

Can STL algorithms be used to create a non fixed size dynamic container? For example a fibonacci sequence whos last/largest element value is less than some const n;

Aucun commentaire:

Enregistrer un commentaire