替换循环以计算符合条件的数字元素

时间:2017-05-09 23:36:13

标签: c++ lambda

我们是否可以通过易于阅读的东西替换strcmp的循环,类似于C#扩展方法?

我维护了传统的C ++,并想知道如何开始向更现代的C ++过渡,并且有大量的代码看起来像这样:

int numberOfPipe = 10;
char* collection[5] = { "pompe","pipe","turbine","pompe", "pipe" };

// Count the pipes in the collection

int nPipeFound = 0;
int nPipe = 5;

for (int idx = 0; idx < nPipe; idx++)
{
    if (strcmp(collection[idx], "pipe") == 0)
        nPipeFound++;
}

cout << nPipeFound << endl;

1 个答案:

答案 0 :(得分:2)

使用标准库:

  1. 使用std::count并使用std::string比较。

    #include <algorithm>
    #include <iostream>
    #include <string>
    
    int main() {
      char const * collection[] = { "pompe","pipe","turbine","pompe","pipe" };
    
      auto n_pipe_found = std::count( std::begin( collection ), std::end( collection ), std::string{"pipe"});
    
      std::cout << n_pipe_found << '\n';
    }
    
  2. 使用std::count_if并编写一个谓词,为您进行C字符串比较。

    #include <algorithm>
    #include <cstring>
    #include <iostream>
    
    int main() {
      char const * collection[] = { "pompe","pipe","turbine","pompe","pipe" };
    
      auto n_pipe_found = std::count_if( std::begin( collection ), std::end( collection ),
                                         [](char const * a) { return std::strcmp(a,"pipe") == 0; } );
    
      std::cout << n_pipe_found << '\n';
    }
    

    您还可以使用[](std::string const& a) { return a == "pipe"; }这样的谓词,并再次使用std::string比较。

  3. 如果您需要对计数进行更精细的控制,请使用std::accumulate

    #include <numeric>
    #include <iostream>
    #include <string>
    
    int main() {
      char const * collection[] = { "pompe","pipe","turbine","pompe","pipe" };
    
      auto n_pipe_found = std::accumulate( std::begin( collection ), std::end( collection ), int{0},
                                       [](int a, std::string const& b) { return a + (b == "pipe"); });
    
      std::cout << n_pipe_found << '\n';
    }