通过递归和迭代实现向量笛卡尔积
您有一个由不同大小的向量项组成的向量,并且您寻求生成一个笛卡尔积他们的元素的产物。
首先,可以采用递归方法:
// Recursive Cartesian product function void cart_product( Vvi& rvvi, // Result vector of vectors Vi& rvi, // Current vector Vvi::const_iterator me, // Current vector in input Vvi::const_iterator end) // Input vector end { if (me == end) { // Push the current result to the final result rvvi.push_back(rvi); return; } // Iterate through the current vector const Vi& mevi = *me; for (Vi::const_iterator it = mevi.begin(); it != mevi.end(); it++) { // Add current element to result rvi.push_back(*it); // Recurse to add subsequent elements cart_product(rvvi, rvi, me + 1, end); // Remove added element for further recursion rvi.pop_back(); } }
现在,考虑迭代方法:
// Iterative Cartesian product function void cart_product( Vvi& out, // Result vector of vectors Vvi& in) // Input vector of vectors { Vd vd; // Vector of iterator structs // Initialize iterators to start of vectors for (Vvi::const_iterator it = in.begin(); it != in.end(); ++it) { Digits d = {(*it).begin(), (*it).end(), (*it).begin()}; vd.push_back(d); } // Iterative loop to generate product vectors while (1) { // Create result vector from iterated elements Vi result; for (Vd::const_iterator it = vd.begin(); it != vd.end(); it++) { result.push_back(*(it->me)); } out.push_back(result); // Increment iterator // Reset iterator at end, increment neighboring iterator for (Vd::iterator it = vd.begin(); ; ) { ++(it->me); if (it->me == it->end) { if (it + 1 == vd.end()) { // End of product return; } else { // Cascade reset it->me = it->begin; ++it; } } else { // Break from loop break; } } } }
以上是如何使用递归和迭代实现向量的笛卡尔积?的详细内容。更多信息请关注PHP中文网其他相关文章!