1
#include <vector>

using namespace std;

class A
{
public:
    A() = default;

    void Add(int n)
    {
        m_count += n;
    }

private:
    int m_count;
};

int main()
{
    vector<int> coll_1 = {1, 2, 3};
    vector<A> coll_2(3);

    // Is there a more elegant way to do the "for loop"?
    for (int i = 0; i < 3; ++i)
    {
        coll_2[i].Add(coll_1[i]);
    }

    return 0;
}

I know there are many new ways (i.e. C++11 flavor) to do the for loop, such as for_each, transform, for (auto& elem : coll), etc.

However, I cannot find an elegant way to do the work as illustrated as above.

Any suggestions?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 2
    What you're doing there can be rewritten as a `zip` until the shortest of the two collections ends, and then on each resulting tuple you can perform the add. `ZipShortest(coll_1, coll_2).ForEach(tup => tup.First.Add(tup.Second))` in pseudo-C#. No idea what could provide this in C++ and how much work it would be. –  Jan 30 '16 at 14:29

1 Answers1

3

You want something that's usually called a 'zip'. Boost has an implementation of it, as you can see in these answers:

Community
  • 1
  • 1
Lauro Moura
  • 750
  • 5
  • 15