Generic function to flatten a container of containers

前端 未结 2 1730
予麋鹿
予麋鹿 2020-12-16 19:35

I am trying to get a better hold on iterators and generic functions. I thought it would be a useful exercise to write a function that converts container1 < contain

相关标签:
2条回答
  • 2020-12-16 20:16

    I found the issue. Thanks to SFINAE (Substitution failure is not an error) your compiler couldn't find the correct template because you are trying to call operator() on start by typing start() (probably a typo). Try this:

    #include <iterator>
    #include <algorithm>
    
    // COCiter == Container of Containers Iterator
    // Oiter == Output Iterator
    template <class COCiter, class Oiter>
    void flatten (COCiter start, COCiter end, Oiter dest) {
        while (start != end) {
            dest = std::copy(start->begin(), start->end(), dest);
            ++start;
        }
    }
    
    0 讨论(0)
  • 2020-12-16 20:31

    std::accumulate can do it for you. You need to gather up the contents of each of the inside vectors into the outside vector.

    vector<vector<int>> v_of_v;
    vector<int> v = std::accumulate(
        v_of_v.begin(), v_of_v.end(),
        vector<int>(),
        [](vector<int> a, vector<int> b) {
            a.insert(a.end(), b.begin(), b.end());
            return a;
        });
    
    0 讨论(0)
提交回复
热议问题