首页 文章

在for循环中避免if语句?

提问于
浏览
113

我有一个名为 Writer 的类,其函数为 writeVector ,如下所示:

void Drawer::writeVector(vector<T> vec, bool index=true)
{
    for (unsigned int i = 0; i < vec.size(); i++) {
        if (index) {
            cout << i << "\t";
        }
        cout << vec[i] << "\n";
    }
}

我'm trying not to have a duplicate code, while still worrying about the performance. In the function, I'我在 for -loop的每一轮都进行 if (index) 检查,即使结果总是一样的 . 这是针对"worrying about the performance"的 .

我可以通过将支票放在我的 for -loop之外来轻松避免这种情况 . 但是,我会得到大量重复的代码:

void Drawer::writeVector(...)
{
    if (index) {
        for (...) {
            cout << i << "\t" << vec[i] << "\n";
        }
    }
    else {
        for (...) {
            cout << vec[i] << "\n";
        }
    }
}

所以这些对我来说都是"bad"解决方案 . 我想知道如何在我的程序中使用它,我仍然需要 if 检查以查看要调用哪一个...

根据问题,多态似乎是一个正确的解决方案 . 但是我看不出我该怎么用呢 . 解决这类问题的首选方法是什么?

这不是一个真正的计划, I'm just interested in learning how this kind of problem should be solved.

4 回答

  • 35

    Pass in the body of the loop as a functor. 它在编译时被内联,没有性能损失 .

    传递变化的想法在C标准库中无处不在 . 它被称为 strategy pattern.

    如果您被允许使用C 11,您可以执行以下操作:

    #include <iostream>
    #include <set>
    #include <vector>
    
    template <typename Container, typename Functor, typename Index = std::size_t>
    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<char> s{'b', 'a', 'c'};
    
        // indices starting at 1 instead of 0
        for_each_indexed(s, [](size_t i, char e) { cout<<i<<'\t'<<e<<'\n'; }, 1u);
    
        cout << "-----" << endl;
    
        vector<int> v{77, 88, 99};
    
        // without index
        for_each_indexed(v, [](size_t , int e) { cout<<e<<'\n'; });
    }
    

    这段代码并不完美,但你明白了 .

    在旧的C 98中它看起来像这样:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    struct with_index {
      void operator()(ostream& out, vector<int>::size_type i, int e) {
        out << i << '\t' << e << '\n';
      }
    };
    
    struct without_index {
      void operator()(ostream& out, vector<int>::size_type i, int e) {
        out << e << '\n';
      }
    };
    
    
    template <typename Func>
    void writeVector(const vector<int>& v, Func f) {
      for (vector<int>::size_type i=0; i<v.size(); ++i) {
        f(cout, i, v[i]);
      }
    }
    
    int main() {
    
      vector<int> 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;
    }
    

    同样,代码远非完美,但它给你的想法 .

  • 38

    在函数中,我正在对for循环的每一轮进行if(索引)检查,即使结果总是相同的 . 这反对“担心表现” .

    如果确实如此,分支预测器在预测(常量)结果方面没有问题 . 因此,这只会在前几次迭代中导致错误预测的轻微开销 . 在性能方面无需担心

    在这种情况下,为了清晰起见,我主张将测试保持在循环内 .

  • 78

    为了扩展Ali的答案,这是完全正确的,但仍然复制了一些代码(循环体的一部分,不幸的是,在使用策略模式时难以避免)...

    在这种特殊情况下,代码重复并不多,但是有一种方法可以减少它,它会派上用场 if the function body is bigger than just a few instructions .

    关键是使用编译器执行 constant folding / dead code elimination 的能力 . 我们可以通过手动将 index 的运行时值映射到编译时值(当只有有限数量的情况时很容易做到 - 在这种情况下为2)并使用非类型模板参数编译时间:

    template<bool index = true>
    //                  ^^^^^^ note: the default value is now part of the template version
    //                         see below to understand why
    void writeVector(const vector<int>& vec) {
        for (size_t i = 0; i < vec.size(); ++i) {
            if (index) { // compile-time constant: this test will always be eliminated
                cout << i << "\t"; // this will only be kept if "index" is true
            }
            cout << vec[i] << "\n";
        }
    }
    
    void writeVector(const vector<int>& vec, bool index)
    //                                            ^^^^^ note: no more default value, otherwise
    //                                            it would clash with the template overload
    {
        if (index) // runtime decision
            writeVector<true>(vec);
            //          ^^^^ map it to a compile-time constant
        else
            writeVector<false>(vec);
    }
    

    这样我们最终得到的编译代码相当于你的第二个代码示例(外部 if /内部 for ),但没有自己复制代码 . 现在我们可以使 writeVector 的模板版本变得如我们想象的那样复杂,总会有一段代码需要维护 .

    请注意模板版本(以非类型模板参数的形式采用编译时常量)和非模板版本(以运行时变量作为函数参数)如何重载 . 这允许您根据需要选择最相关的版本,在两种情况下都具有相似且易于记忆的语法:

    writeVector<true>(vec);   // you already know at compile-time which version you want
                              // no need to go through the non-template runtime dispatching
    
    writeVector(vec, index);  // you don't know at compile-time what "index" will be
                              // so you have to use the non-template runtime dispatching
    
    writeVector(vec);         // you can even use your previous syntax using a default argument
                              // it will call the template overload directly
    
  • 0

    在大多数情况下,您的代码已经具有良好的性能和可读性 . 一个好的编译器能够检测循环不变量并进行适当的优化 . 请考虑以下与您的代码非常接近的示例:

    #include <cstdio>
    #include <iterator>
    
    void write_vector(int* begin, int* end, bool print_index = false) {
        unsigned index = 0;
        for(int* it = begin; it != end; ++it) {
            if (print_index) {
                std::printf("%d: %d\n", index, *it);
            } else {
                std::printf("%d\n", *it);
            }
            ++index;
        }
    }
    
    int my_vector[] = {
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    };
    
    
    int main(int argc, char** argv) {
        write_vector(std::begin(my_vector), std::end(my_vector));
    }
    

    我使用以下命令行来编译它:

    g++ --version
    g++ (GCC) 4.9.1
    Copyright (C) 2014 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    g++ -O3 -std=c++11 main.cpp
    

    然后,让我们转储汇编:

    objdump -d a.out | c++filt > main.s
    

    write_vector 的结果程序集是:

    00000000004005c0 <write_vector(int*, int*, bool)>:
      4005c0:   48 39 f7                cmp    %rsi,%rdi
      4005c3:   41 54                   push   %r12
      4005c5:   49 89 f4                mov    %rsi,%r12
      4005c8:   55                      push   %rbp
      4005c9:   53                      push   %rbx
      4005ca:   48 89 fb                mov    %rdi,%rbx
      4005cd:   74 25                   je     4005f4 <write_vector(int*, int*, bool)+0x34>
      4005cf:   84 d2                   test   %dl,%dl
      4005d1:   74 2d                   je     400600 <write_vector(int*, int*, bool)+0x40>
      4005d3:   31 ed                   xor    %ebp,%ebp
      4005d5:   0f 1f 00                nopl   (%rax)
      4005d8:   8b 13                   mov    (%rbx),%edx
      4005da:   89 ee                   mov    %ebp,%esi
      4005dc:   31 c0                   xor    %eax,%eax
      4005de:   bf a4 06 40 00          mov    $0x4006a4,%edi
      4005e3:   48 83 c3 04             add    $0x4,%rbx
      4005e7:   83 c5 01                add    $0x1,%ebp
      4005ea:   e8 81 fe ff ff          callq  400470 <printf@plt>
      4005ef:   49 39 dc                cmp    %rbx,%r12
      4005f2:   75 e4                   jne    4005d8 <write_vector(int*, int*, bool)+0x18>
      4005f4:   5b                      pop    %rbx
      4005f5:   5d                      pop    %rbp
      4005f6:   41 5c                   pop    %r12
      4005f8:   c3                      retq   
      4005f9:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)
      400600:   8b 33                   mov    (%rbx),%esi
      400602:   31 c0                   xor    %eax,%eax
      400604:   bf a8 06 40 00          mov    $0x4006a8,%edi
      400609:   48 83 c3 04             add    $0x4,%rbx
      40060d:   e8 5e fe ff ff          callq  400470 <printf@plt>
      400612:   49 39 dc                cmp    %rbx,%r12
      400615:   75 e9                   jne    400600 <write_vector(int*, int*, bool)+0x40>
      400617:   eb db                   jmp    4005f4 <write_vector(int*, int*, bool)+0x34>
      400619:   0f 1f 80 00 00 00 00    nopl   0x0(%rax)
    

    我们可以看到,在函数的乞求时,我们检查值并跳转到两个可能的循环之一:

    4005cf:   84 d2                   test   %dl,%dl
      4005d1:   74 2d                   je     400600 <write_vector(int*, int*, bool)+0x40>
    

    当然,这仅在编译器能够检测到条件是实际不变的情况下才有效 . 通常,它完全适用于标志和简单的内联函数 . 但如果条件“复杂”,请考虑使用其他答案的方法 .

相关问题