Sunday 15 January 2012

C++ Can I Substitute Nested For Loop with 1 Loop -



C++ Can I Substitute Nested For Loop with 1 Loop -

so i've been trying code simplification, because i'm not fond of having nested loops i'm experiencing problem trying simplify below code. code functions fine , intended (code below stripped down!).

int fill{200}, wid{600}, hei{400}; (int w{ 0 }; w < fill; w++) { (int h{ 0 }; h < hei; h++) { int offset{ w + h * (wid + fill) } //offset used traverse 1d array "fill" amount of times. /*before: 000000 000000 000000 000000 after: 110000 110000 110000 110000*/ } }

i've tried reproduce same output 1 less loop either don't right result or go outside of array. i'm wondering can done?

i not sure if recommend it, science... there go. gives ok me. thought simple. combine 2 numbers 1 multiplication, , retrieve them via partition , modulo.

just remember sure not overflow @ multiplication. leave note did not check if types chosen correctly. illustration lone int offset{ w + h * (wid + fill) }; raises flag me. below code math/method mainly.

#include <iostream> #include <vector> using namespace std; int main() { std::vector<int> loop1, loop2; int fill{200}, wid{600}, hei{400}; (int w{ 0 }; w < fill; w++) { (int h{ 0 }; h < hei; h++) { int offset{ w + h * (wid + fill) }; loop1.push_back(offset); } } (int i{ 0 }; < fill*hei; i++) { int w = / hei; int h = % hei; int offset{ w + h * (wid + fill) }; loop2.push_back(offset); } if (loop2 == loop1) cout << "ok\n"; else cout << "not ok\n"; homecoming 0; }

c++ for-loop nested-loops simplification

No comments:

Post a Comment