Howto create combinations of several vectors without hardcoding loops in C++?

前端 未结 10 969
慢半拍i
慢半拍i 2020-11-29 08:40

I have several data that looks like this:

Vector1_elements = T,C,A
Vector2_elements = C,G,A
Vector3_elements = C,G,T
..... up to ...
VectorK_elements = ...

         


        
10条回答
  •  情深已故
    2020-11-29 09:07

    A C++0x solution. Provided, of course, your compiled supports it (currently GCC 4.5 and VS2010, I think).

    The following compiles and works with GCC 4.5 using -std=c++0x switch. The use of variadic templates makes it possible to combine arbitrary number of containers. I am sure you can come up with a more idiomatic solution.

    #include        
    #include 
    #include 
    #include 
    #include 
    
    typedef std::vector myvec;
    
    // Base case.
    void combine2(const std::string &row) {
        std::cout << row << std::endl;
    }
    
    // Recursive variadic template core function.
    template
    void combine2(const std::string &row, const T0& cont0, T...cont_rest) {
        for (auto i = cont0.begin(); i != cont0.end(); ++i) {
            std::stringstream ss;
            ss << row << *i;
            combine2(ss.str(), cont_rest...);
        }
    }
    
    // The actual function to call.
    template
    void combine(T...containers) {
        combine2("", containers...);
    }
    
    int main() {
        myvec v1 = {"T", "C", "A"}, v2 = {"C", "G", "A"}, v3 = {"C", "G", "T"};
    
        combine(v1);
        combine(v1, v2);
        combine(v1, v2, v3);
    
        // Or even...
        std::vector v4 = {"T", "C", "A"};
        std::vector v5 = {'C', 'G', 'A'};
        std::vector v6 = {1 ,2 ,3};
    
        combine(v4);
        combine(v4, v5);
        combine(v4, v5, v6);
    
        return 0;
    }
    

提交回复
热议问题