0

In the following program two templates are provided to execute a function over either two or three ranges.

#include <algorithm>
#include <iterator>

template <typename R1, typename R2, typename Handler>
void for_eaches(R1 s1,R1 e1,R2 s2,R2 e2,Handler handler)
{
    for (; s1!=e1 && s2!=e2; ++s1,++s2)
        handler(*s1,*s2);
}

template <typename R1, typename R2, typename R3, typename Handler>
void for_eaches(R1 s1,R1 e1,R2 s2,R2 e2, R3 s3, R3 e3, Handler handler)
{
    for (; s1!=e1 && s2!=e2 && s3!=e3; ++s1,++s2,++s3)
        handler(*s1,*s2,*s3);
}

////How could the following be written for the general case?
//template <typename... Iterators, typename Handler>
//void for_eaches(Iterators... iterators,Handler handler)
//{
//  for (; iterator<i>!=iterator<i+1>...; ++iterator<i>...)
//      handler(*iterator...);
//}

int main()
{
    char text[]{"a abc text"};
    char search[]{'a','b','c','d','e'};
    char replace[]{'f','g','h','i','j'};
    int add[]{1,0,2,3,1};

    for (auto s{std::begin(search)},r{std::begin(replace)}; s!=std::end(search) && r!=std::end(replace); ++s,++r)
        std::replace(std::begin(text),std::end(text),*s,*r);

    std::swap(search,replace);

    for_eaches(
        std::begin(search),std::end(search),
        std::begin(replace),std::end(replace),
        [&text](auto& s,auto& r) {std::replace(std::begin(text),std::end(text),s,r); });

    std::swap(search,replace);

    for_eaches(
        std::begin(search),std::end(search),
        std::begin(replace),std::end(replace),
        std::begin(add),std::end(add),
        [&text](auto& s,auto& r, auto&a) 
            {
                auto r_added{r};
                r_added+=a;
                std::replace(std::begin(text),std::end(text),s,r_added); 
            }
    );

    return 0;
}

How could the template be written for the general case so that any number of ranges may be provided?

wally
  • 10,717
  • 5
  • 39
  • 72
  • The first of your overloads seems pretty much like [`std::transform`](http://en.cppreference.com/w/cpp/algorithm/transform) (look at the third overload in that reference) to me. – Some programmer dude Jun 18 '16 at 15:43
  • 4
    Does your compiler not warn you that `s1!=e1,s2!=e2,s3!=e3` is useless? –  Jun 18 '16 at 15:44
  • @hvd Good catch. Compiling with all warnings from now on... – wally Jun 18 '16 at 15:58

0 Answers0