nested generic container iteration C++

pinetreepatzer

I am teaching myself to use templates and have been wondering if there is a way to iterate over nested containers in a generic fashion. I have seen examples which iterate over single containers in this way.

Here is a function example for a vector of vectors. I would like to make this work for vectors of valarrays and arrays of arrays as well without having to write a separate function for each. Thanks in advance.

// matrix sum of two vectors of vectors
template<typename T>
vector<vector<T>> sum(vector<vector<T>> const &M1,
                      vector<vector<T>> const &M2) {
    vector<vector<T>> MS(M2.size(), vector<T>(M2[0].size()));
    for (unsigned int i = 0; i < MS.size(); ++i) {
        for (unsigned int j = 0; j < MS[i].size(); ++j) {
            MS[i][j] = M1[i][j] + M2[i][j];
        }
    }
}
Otomo

I would suggest the following (in the STL-Style):

// matrix sum of two twodimensional containers
template<typename InputIterator, typename OutputIterator>
OutputIterator sum(InputIterator first1, InputIterator last1,
                   InputIterator first2, OutputIterator result) {
    if(first1 == last1) { return result; } // Check for empty container

    for (; first1 != last1; ++first1, ++first2) {         
        std::transform(std::begin(*first1), std::end(*first1),
                       std::begin(*first2), std::begin(*result),
                       std::add<void>{});
        ++result;
        // Please be aware that this only works if the result container
        // has already the dimensions of the input containers.
        // std::back_inserter does not work with this implementation.
    }
    return result;
}

Algorithms of this style should work with normal arrays, vectors, std::arrays, etc...

Note: This Algorithm is not tested. Edit: This Algorithm works in c++14.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related