samedi 30 janvier 2016

How to iterate two vectors in one loop in C++11? [duplicate]

This question already has an answer here:

#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?

Aucun commentaire:

Enregistrer un commentaire