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

编程入门 行业动态 更新时间:2024-10-25 21:33:04

【c++】<a href=https://www.elefans.com/category/jswz/34/1771029.html style=遍历容器,哪一种方法速度最快?"/>

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

终于有一个简单的每日一题!写完的时候甚至代码还没有编译结束!刚好借今天的每日一题探究一下一直以来的一些疑惑:容器的遍历。
题目大概是这样的:

我们一眼就看到了容器的遍历!!那么众所周知,容器的遍历最常用的有三种:

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

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

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <time.h>
#include <iomanip>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;
}

运行一遍,得到了这样的输出:

Amazing!可以看到这场比赛,匿名函数输得一塌糊涂,反而是朴实无华的for夺魁!
这到底是为什么呢?

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

更多推荐

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

本文发布于:2023-12-04 07:40:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1660215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   种方法   容器   速度最快

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!