Avoiding if statement inside a for loop?

后端 未结 4 2008
南旧
南旧 2020-12-04 06:54

I have a class called Writer that has a function writeVector like so:

void Drawer::writeVector(vector vec, bool index=true         


        
4条回答
  •  粉色の甜心
    2020-12-04 07:09

    Pass in the body of the loop as a functor. It gets inlined at compile-time, no performance penalty.

    The idea of passing in what varies is ubiquitous in the C++ Standard Library. It is called the strategy pattern.

    If you are allowed to use C++11, you can do something like this:

    #include 
    #include 
    #include 
    
    template 
    void for_each_indexed(const Container& c, Functor f, Index index = 0) {
    
        for (const auto& e : c)
            f(index++, e);
    }
    
    int main() {
    
        using namespace std;
    
        set s{'b', 'a', 'c'};
    
        // indices starting at 1 instead of 0
        for_each_indexed(s, [](size_t i, char e) { cout< v{77, 88, 99};
    
        // without index
        for_each_indexed(v, [](size_t , int e) { cout<

    This code is not perfect but you get the idea.

    In old C++98 it looks like this:

    #include 
    #include 
    using namespace std;
    
    struct with_index {
      void operator()(ostream& out, vector::size_type i, int e) {
        out << i << '\t' << e << '\n';
      }
    };
    
    struct without_index {
      void operator()(ostream& out, vector::size_type i, int e) {
        out << e << '\n';
      }
    };
    
    
    template 
    void writeVector(const vector& v, Func f) {
      for (vector::size_type i=0; i v;
      v.push_back(77);
      v.push_back(88);
      v.push_back(99);
    
      writeVector(v, with_index());
    
      cout << "-----" << endl;
    
      writeVector(v, without_index());
    
      return 0;
    }
    

    Again, the code is far from perfect but it gives you the idea.

提交回复
热议问题