mercredi 26 juillet 2017

Assigning multi-dimensional vectors with different types

Suppose I have a std::vector<std::vector<double>> d and want to assign it to a std::vector<std::vector<int>> i; the best I could come up with was:

#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<vector<double>> d = { {1.0, 2.0}, {3.0, 4.0} };
    vector<vector<int>>    i;

    for_each(begin(d), end(d), [&i](vector<double> &x) {
            i.emplace_back(begin(x), end(x));
        }
    );

    return 0;
}

If both vectors were using the same type internally, I could just use the assignment operator (see C++ copying multidimensional vector):

i = d;

If the vectors were storing different types internally, but one-dimensional, I could do:

i.assign(begin(d), end(d));

Both of those are really obvious in their intention, which I don't feel is the case with my solution for the multi-dimensional approach. Is there a better way, or an accepted idiom, to do this?

Aucun commentaire:

Enregistrer un commentaire