General function for smoothing container containers

I am trying to better hold on iterators and common functions. I thought it would be a useful exercise to write a function that converts container1 < container2 <type> > to container3 <type> . For example, it should be able to convert vector< deque<int> > to list<int> .

I realized that all access to the container should be through iterators, such as functions in <algorithm> .

Here is my code:

 #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) { using namespace std; while (start != end) { dest = copy(start->begin(), start()->end(), dest); ++start; } } 

But when I try to call it in the following code:

 int main () { using namespace std; vector< vector<string> > splitlines; vector<string> flat; /* some code to fill SPLITLINES with vectors of strings */ flatten(splitlines.begin(), splitlines.end(), back_inserter(flat)); } 

I get a huge C ++ template error message, undefined reference to void flatten< ... pages of templates ...

It seems to me that my code is too easy to write, and I need something else to make the data type in the internal containers match the data type in the output container. But I do not know what to do.

+6
source share
1 answer

I found a problem. Thanks to SFINAE (replacement failure is not an error) your compiler could not find the correct template because you are trying to call operator() on start by typing start() (possibly a typo). Try the following:

 #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; } } 
+8
source

Source: https://habr.com/ru/post/890875/


All Articles