I have been looking at some algorithms and I am wondering why some of them don't also have a variation that takes in a container.
For example, find
can take in a container and value and the algorithm can internally iterator over the container by calling begin
and end
of the container. Same with unique_copy
where it seems more useful to me to pass a container and the algorithm use push_back
instead of requiring an iterator where I would be forced to resize the array to the maximum element count. for_each
is another such example.
I am sure there are good reasons I don't know about?
There are two main reasons I can see:
std::copy()
you have two ranges, each one of them independently wants to be specified either as range (the proper abstraction isn't containers, BTW, but rather rangers) or a pair of iterators, making it already 4 overloads.std::find()
which clearly returns an iterator when it gets iterators as arguments. When given a range, it may actually be much more reasonable to return another range. To make matters worse, unless you have a single pass range initially (e.g., something reading from a stream) there is even a choice of two different ranges, i.e., begin to found object, and found object to end. Another dimension could be a choice of getting a copy of the chosen range rather than a range delimited by iterators.When STL was proposed initially, it was considered Crazy Talk in the first place! Trying to convince people to open another major can of worms to deal with ranges properly could have easily killed off the entire idea. The immediate follow-up question then becomes: Why wasn't this changed? ... and there are two answers to this question as well:
If you want to put the result into a container without preallocating the elements, use an insert iterator. For example:
std::vector<int> elements;
// ...
std::vector<int> uniqueElements;
std::unique_copy(elements.begin(), elements.end(),
std::back_inserter(uniqueElements));
The algorithms that take iterators are the most general purpose. There's nothing preventing you from creating your own convenience functions that call the standard algorithms with the proper parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With