Clean ways to write multiple 'for' loops

前端 未结 16 953
傲寒
傲寒 2020-12-22 15:22

For an array with multiple dimensions, we usually need to write a for loop for each of its dimensions. For example:

vector< vector< vector         


        
16条回答
  •  不思量自难忘°
    2020-12-22 15:41

    One technique I've used is templates. E.g.:

    template void do_something_on_A(std::vector &vec) {
        for (auto& i : vec) { // can use a simple for loop in C++03
            do_something_on_A(i);
        }
    }
    
    void do_something_on_A(int &val) {
        // this is where your `do_something_on_A` method goes
    }
    

    Then you simply call do_something_on_A(A) in your main code. The template function gets created once for each dimension, the first time with T = std::vector>, the second time with with T = std::vector.

    You could make this more generic using std::function (or function-like objects in C++03) as a second argument if you want:

    template void do_something_on_vec(std::vector &vec, std::function &func) {
        for (auto& i : vec) { // can use a simple for loop in C++03
            do_something_on_vec(i, func);
        }
    }
    
    template void do_something_on_vec(T &val, std::function &func) {
        func(val);
    }
    

    Then call it like:

    do_something_on_vec(A, std::function(do_something_on_A));
    

    This works even though the functions have the same signature because the first function is a better match for anything with std::vector in the type.

提交回复
热议问题