【c++】遍历容器,哪一种方法速度最快?

终于有一个简单的每日一题!写完的时候甚至代码还没有编译结束!刚好借今天的每日一题探究一下一直以来的一些疑惑:容器的遍历。
题目大概是这样的:
【c++】遍历容器,哪一种方法速度最快?_第1张图片
我们一眼就看到了容器的遍历!!那么众所周知,容器的遍历最常用的有三种:

  1. 基础for,也就是for(int i = 0; i < 10; i++)这种格式
  2. c++11 的for
  3. algorithm中的for_each

下面蘸着这个题写三种遍历,看看执行时间:

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int countSeniors(vector<string> &details)
{
  int cnt = 0;
  for_each(details.begin(), details.end(), [&cnt](const string &detail)
           {
            if (detail[11] > '6' || (detail[11] == '6' && detail[12] != '0')) {
                cnt++;
            } });

  return cnt;
}

int countSeniors2(vector<string> &details)
{
  int cnt = 0;
  for (const auto &detail : details)
  {
    if (detail[11] > '6' || (detail[11] == '6' && detail[12] != '0'))
    {
      cnt++;
    }
  }
  return cnt;
}

int countSeniors3(vector<string> &details)
{
  int cnt = 0;
  for (int i = 0; i < static_cast<int>(details.size()); i++)
  {
    if (details[i][11] > '6' || (details[i][11] == '6' && details[i][12] != '0'))
    {
      cnt++;
    }
  }
  return cnt;
}

int main()
{
  vector<string> details = {"7868190130M7522", "5303914400F9211", "9273338290F4010"};
  cout << setprecision(10);
  {
    clock_t startT, finishT;
    startT = clock();
    countSeniors(details);
    finishT = clock();
    double duration = static_cast<double>(finishT - startT) / CLOCKS_PER_SEC;
    cout << "匿名函数: " << duration << endl;
  }
  {
    clock_t startT, finishT;
    startT = clock();
    countSeniors2(details);
    finishT = clock();
    double duration = static_cast<double>(finishT - startT) / CLOCKS_PER_SEC;
    cout << "c++11 for: " << duration << endl;
  }
  {
    clock_t startT, finishT;
    startT = clock();
    countSeniors3(details);
    finishT = clock();
    double duration = static_cast<double>(finishT - startT) / CLOCKS_PER_SEC;
    cout << "基础for: " << duration << endl;
  }
  {
    clock_t startT, finishT;
    startT = clock();
    for (int i = 0; i < 100; i++)
    {
      countSeniors(details);
    }
    finishT = clock();
    double duration = static_cast<double>(finishT - startT) / CLOCKS_PER_SEC;
    cout << "100 次:匿名函数: " << duration << endl;
  }
  {
    clock_t startT, finishT;
    startT = clock();
    for (int i = 0; i < 100; i++)
    {
      countSeniors2(details);
    }
    finishT = clock();
    double duration = static_cast<double>(finishT - startT) / CLOCKS_PER_SEC;
    cout << "100 次:c++11 for: " << duration << endl;
  }
  {
    clock_t startT, finishT;
    startT = clock();
    for (int i = 0; i < 100; i++)
    {
      countSeniors3(details);
    }
    finishT = clock();
    double duration = static_cast<double>(finishT - startT) / CLOCKS_PER_SEC;
    cout << "100 次:基础for: " << duration << endl;
  }
  return 0;
}

运行一遍,得到了这样的输出:
【c++】遍历容器,哪一种方法速度最快?_第2张图片
Amazing!可以看到这场比赛,匿名函数输得一塌糊涂,反而是朴实无华的for夺魁!
这到底是为什么呢?

–没写完,代码跑完了,一会儿干完活再写

你可能感兴趣的:(Leetcode题解,c++,c++,开发语言,性能优化)