[英]Creating N nested for-loops
有沒有辦法創建表單的for循環
for(int i = 0; i < 9; ++i) {
for(int j = 0; j < 9; ++i) {
//...
for(int k = 0; k < 9; ++k) { //N-th loop
在編譯時不知道N. 理想情況下,我試圖找出一種循環通過數字向量的單獨元素的方法,以便在用不同的數字替換一定數量的數字時創建每個可能的數字。
您可以使用遞歸而不是基本條件 -
void doRecursion(int baseCondition){
if(baseCondition==0) return;
//place your code here
doRecursion(baseCondition-1);
}
現在,您無需在編譯時提供baseCondition
值。 您可以在調用doRecursion()
方法時提供它。
這是一個很好的小類,可以通過基於范圍的for循環迭代多索引:
#include<array>
template<int dim>
struct multi_index_t
{
std::array<int, dim> size_array;
template<typename ... Args>
multi_index_t(Args&& ... args) : size_array(std::forward<Args>(args) ...) {}
struct iterator
{
struct sentinel_t {};
std::array<int, dim> index_array = {};
std::array<int, dim> const& size_array;
bool _end = false;
iterator(std::array<int, dim> const& size_array) : size_array(size_array) {}
auto& operator++()
{
for (int i = 0;i < dim;++i)
{
if (index_array[i] < size_array[i] - 1)
{
++index_array[i];
for (int j = 0;j < i;++j)
{
index_array[j] = 0;
}
return *this;
}
}
_end = true;
return *this;
}
auto& operator*()
{
return index_array;
}
bool operator!=(sentinel_t) const
{
return !_end;
}
};
auto begin() const
{
return iterator{ size_array };
}
auto end() const
{
return typename iterator::sentinel_t{};
}
};
template<typename ... index_t>
auto multi_index(index_t&& ... index)
{
static constexpr int size = sizeof ... (index_t);
auto ar = std::array<int, size>{std::forward<index_t>(index) ...};
return multi_index_t<size>(ar);
}
基本思想是使用一個包含許多dim
指數的數組,然后實現operator++
以適當地增加這些索引。
用它作為
for(auto m : multi_index(3,3,4))
{
// now m[i] holds index of i-th loop
// m[0] goes from 0 to 2
// m[1] goes from 0 to 2
// m[2] goes from 0 to 3
std::cout<<m[0]<<" "<<m[1]<<" "<<m[2]<<std::endl;
}
你可以使用遞歸函數:
void loop_function(/*params*/,int N){
for(int i=0;i<9;++i){
if(N>0) loop_function(/*new params*/,N-1);
}
這將遞歸調用loop_function N次,而每個函數將迭代調用loop_function
以這種方式編程可能有點困難,但它應該做你想要的
您可以使用遞歸調用:
void runNextNestedFor(std::vector<int> counters, int index)
{
for(counters[index] = 0; counters[index] < 9; ++counters[index]) {
// DO
if(index!=N)
runNextNestedFor(counters, index+1);
}
}
第一次稱它為:
std::vectors<int> counters(N);
runNextNestedFor(counters, 0);
我寫了一些C ++ 11代碼,為自己實現了一個N嵌套的for循環。 這是代碼的主要部分,可以用作單個.hpp導入(我將其命名為nestedLoop.hpp):
#ifndef NESTEDLOOP_HPP
#define NESTEDLOOP_HPP
#include <vector>
namespace nestedLoop{
class nestedLoop {
public:
//Variables
std::vector<int> maxes;
std::vector<int> idxes; //The last element is used for boundary control
int N=0;
int nestLevel=0;
nestedLoop();
nestedLoop(int,int);
nestedLoop(int,std::vector<int>);
void reset(int numberOfNests, int Max);
void reset(int numberOfNests, std::vector<int> theMaxes);
bool next();
void jumpNest(int theNest);
private:
void clear();
};
//Initialisations
nestedLoop::nestedLoop(){}
nestedLoop::nestedLoop(int numberOfNests, int Max) {
reset(numberOfNests, Max);
}
nestedLoop::nestedLoop(int numberOfNests, std::vector<int> theMaxes) {
reset(numberOfNests, theMaxes);
}
void nestedLoop::clear(){
maxes.clear();
idxes.clear();
N = 0;
nestLevel = 0;
}
//Reset the scene
void nestedLoop::reset(int numberOfNests, int Max){
std::vector<int> theMaxes;
for(int i =0; i < numberOfNests; i++) theMaxes.push_back(Max);
reset(numberOfNests, theMaxes);
}
void nestedLoop::reset(int numberOfNests, std::vector<int> theMaxes){
clear();
N = numberOfNests;
maxes=theMaxes;
idxes.push_back(-1);
for(int i=1; i<N; i++) idxes.push_back(theMaxes[i]-1);
}
bool nestedLoop::next(){
idxes[N-1]+=1;
for(int i=N-1; i>=0; i--){
if(idxes[i]>=maxes[i]) {
idxes[i] = 0;
if(i){ //actually, if i > 0 is needed
idxes[i-1] += 1;
}else{
return false;
}
}else{
nestLevel = i;
break;
}
}
return true;
}
void nestedLoop::jumpNest(int theNest){
for(int i = N-1; i>theNest; i--) {
idxes[i] = maxes[i]-1;
}
}
}
#endif // NESTEDLOOP_HPP
以下是預期輸出的示例:
#include <iostream>
#include "stlvecs.hpp"
#include "nestedLoop.hpp"
int main(){
nestedLoop::nestedLoop looper;
std::vector<int> maxes = {2, 3, 2, 2};
looper.reset(4,maxes);
int i = 0;
while(looper.next()){
std::cout << "Indices: " << looper.idxes << ", Last nest incremented: " << looper.nestLevel << std::endl;
if(i == 5){
std::cout << "...Jump Second Nest (index 1)..." << std::endl;
looper.jumpNest(1);
}
i++;
}
}
/* Expected output
Indices: 4 0 0 0 0 , Last nest incremented: 0
Indices: 4 0 0 0 1 , Last nest incremented: 3
Indices: 4 0 0 1 0 , Last nest incremented: 2
Indices: 4 0 0 1 1 , Last nest incremented: 3
Indices: 4 0 1 0 0 , Last nest incremented: 1
Indices: 4 0 1 0 1 , Last nest incremented: 3
...Jump Second Nest (index 1)...
Indices: 4 0 2 0 0 , Last nest incremented: 1
Indices: 4 0 2 0 1 , Last nest incremented: 3
Indices: 4 0 2 1 0 , Last nest incremented: 2
Indices: 4 0 2 1 1 , Last nest incremented: 3
Indices: 4 1 0 0 0 , Last nest incremented: 0
Indices: 4 1 0 0 1 , Last nest incremented: 3
Indices: 4 1 0 1 0 , Last nest incremented: 2
Indices: 4 1 0 1 1 , Last nest incremented: 3
Indices: 4 1 1 0 0 , Last nest incremented: 1
Indices: 4 1 1 0 1 , Last nest incremented: 3
Indices: 4 1 1 1 0 , Last nest incremented: 2
Indices: 4 1 1 1 1 , Last nest incremented: 3
Indices: 4 1 2 0 0 , Last nest incremented: 1
Indices: 4 1 2 0 1 , Last nest incremented: 3
Indices: 4 1 2 1 0 , Last nest incremented: 2
Indices: 4 1 2 1 1 , Last nest incremented: 3
*/
我將以給定的示例代碼的面值取OP,並假設所要求的是一個通過任意基數為10的解決方案。 (我的觀點基於評論“理想情況下,我試圖找出一種循環通過數字向量的單獨元素來創建每個可能數字的方法”。
該解決方案具有循環,該循環通過基數10中的數字向量計數,並將每個連續值傳遞給輔助函數(doThingWithNumber)。 出於測試目的,我有這個助手只需打印出數字。
#include <iostream>
using namespace std;
void doThingWithNumber(const int* digits, int numDigits)
{
int i;
for (i = numDigits-1; i>=0; i--)
cout << digits[i];
cout << endl;
}
void loopOverAllNumbers(int numDigits)
{
int* digits = new int [numDigits];
int i;
for (i = 0; i< numDigits; i++)
digits[i] = 0;
int maxDigit = 0;
while (maxDigit < numDigits) {
doThingWithNumber(digits, numDigits);
for (i = 0; i < numDigits; i++) {
digits[i]++;
if (digits[i] < 10)
break;
digits[i] = 0;
}
if (i > maxDigit)
maxDigit = i;
}
}
int main()
{
loopOverAllNumbers(3);
return 0;
}
我使用這個解決方案:
unsigned int dim = 3;
unsigned int top = 5;
std::vector<unsigned int> m(dim, 0);
for (unsigned int i = 0; i < pow(top,dim); i++)
{
// What you want to do comes here
// |
// |
// v
// -----------------------------------
for (unsigned int j = 0; j < dim; j++)
{
std::cout << m[j] << ",";
}
std::cout << std::endl;
// -----------------------------------
// Increment m
if (i == pow(top, dim) - 1) break;
unsigned int index_to_increment = dim - 1;
while(m[index_to_increment] == (top-1)) {
m[index_to_increment] = 0;
index_to_increment -= 1;
}
m[index_to_increment] += 1;
}
它當然可以優化和調整,但它工作得很好,您不需要將參數傳遞給遞歸函數。 使用單獨的函數來遞增多索引:
typedef std::vector<unsigned int> ivec;
void increment_multi_index(ivec &m, ivec const & upper_bounds)
{
unsigned int dim = m.size();
unsigned int i = dim - 1;
while(m[i] == upper_bounds[i] - 1 && i>0) {
m[i] = 0;
i -= 1;
}
m[i] += 1;
}
int main() {
unsigned int dim = 3;
unsigned int top = 5;
ivec m(dim, 0);
ivec t(dim, top);
for (unsigned int i = 0; i < pow(top,dim); i++)
{
// What you want to do comes here
// |
// |
// v
// -----------------------------------
for (unsigned int j = 0; j < dim; j++)
{
std::cout << m[j] << ",";
}
std::cout << std::endl;
// -----------------------------------
// Increment m
increment_multi_index(m, t);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.