c++ - Cascade application of merging member function on vector of vectors with constraint -


i have following vector of vectors:

v = std::vector<std::vector<mytype> > 

the vectors contained in v not of same length. mytype has member function merge following signature:

bool mytype::merge(mytype in, mytype &out); 

this member function takes self , in , checks if can merged out. if so, out set merged result , function returns true. otherwise false returned , out not modified.

i want go through each vector in v , possible combined merges final result std::vector. example, if v contains 3 vectors a, b, c 3 elements each, want vector following result:

a_0 - b_0 - c_0 a_0 - b_0 _ c_1 a_0 - b_0 _ c_2 a_0 - b_1 - c_0 a_0 - b_1 _ c_1 a_0 - b_1 _ c_2 a_0 - b_2 - c_0 a_0 - b_2 _ c_1 a_0 - b_2 _ c_2 a_1 - b_0 ... etc 

the merged result should not in result vector if @ point merge returns false.

the explanation bit lengthy have feeling should not difficult, , have feeling there simple way of accomplishing stl functionality, don't see it.

this sounds recursive problem, merging n-dimensional cartesian product of vectors' elements:

you want merge each element of outcomes of merging possible combinations of merging elements b,c,... , put result vector, i.e. merge first dimension result of cartesian merge product of remaining n-1 dimensions. recursion's end last dimension:

typedef std::vector<std::vector<mytype>>::const_iterator vviter; std::vector<mytype> cartesianmerge(vviter start, vviter end) {     auto const& currentvector = *start;     if (start+1 == end) return currentvector; //end recursion     auto mergewith = cartesianmerge(start+1, end); //recursie     std::vector<mytype> results;    mytype temp;    (auto const& lhs : currentvector)      (auto const& rhs : mergewith )         if (lhs.merge(rhs, temp)) results.push_back(temp);     return results; }  int main() {   auto v = std::vector<std::vector<mytype> >{ /* ... fill it! ... */ };    auto allmerged = cartesianmerge(std::begin(v), std::end(v)); } 

this maybe generalized using standard algorithms std::transform since it's conditinal transformation (no result if merge fails), not clearer.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -