-1

There are a lot of functions in the C++ standard library that take in an iterator pointing to the start of some collection, followed by an iterator pointing to the end of it. Quite often we want to operate on all the elements in a collection, rather than some subset, so we end up with a lot of repetition of .begin() and .end(). Is there a more concise way of writing this in C++?

For example:

std::vector<int> i = {1,2,3,4,5};

int sum = std::accumulate(i.begin(), i.end(), 0);

It would be nice if we could write something like std::accumulate(i, 0) instead. Is there a way of doing something like this?

Rob Gilton
  • 401
  • 4
  • 16
  • Create a simple template function on your own, delegating to `std::accumulate(...)`? What's bothering you? – πάντα ῥεῖ Jun 02 '23 at 15:41
  • 4
    `namespace std::ranges`? – 273K Jun 02 '23 at 15:42
  • If you have a recent enough compiler, how about [ranges](https://en.cppreference.com/w/cpp/ranges)? Or if it's not new enough, [the range library](https://github.com/ericniebler/range-v3) that the standard is based on? – Some programmer dude Jun 02 '23 at 15:42
  • C++20 has [ranges](https://en.cppreference.com/w/cpp/ranges), so you can much easier represent operations on containers. – Eljay Jun 02 '23 at 15:43
  • 1
    Slightly surprised that there isn't a `ranges` version of `accumulate`. For a lot of algorithms that take a begin-end iterator pair, there's a [constrained algorithm](https://en.cppreference.com/w/cpp/algorithm/ranges) in C++20 that takes a range instead. – Nathan Pierson Jun 02 '23 at 15:43
  • @Nathan Not all at once https://stackoverflow.com/questions/63933163/why-didnt-accumulate-make-it-into-ranges-for-c20 – 273K Jun 02 '23 at 15:44
  • 1
    Eric Niebler's **Range v3** has an [accumulate_ints](https://github.com/ericniebler/range-v3/blob/master/example/accumulate_ints.cpp) example. – Eljay Jun 02 '23 at 15:57

1 Answers1

2

C++20 introduced ranges.

For older compilers, or for more completeness, you can use Boost.Range

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172