c++容器遍历五种方式

容器遍历

#include <QElapsedTimer>
std::vector<int> vector(999999,999);
QElapsedTimer time;//测试耗时时间 类 用法
time.start();
time.elapsed();

第一种

利用for循环,获取容器头和尾地址,从头开始遍历直到末尾
    for(auto it = vector.begin(); it != vector.end(); it++)
    {
        std::cout << *it << " ";
    }

第二种

利用for循环,加上引用,大大提高运行效率

    for(auto &it : vector)
    {
        std::cout << it << " ";
    }

第三种

利用foreach遍历,未加上引用,运行效率较低

qt容器遍历方式

    foreach (auto it, vector) {
        std::cout << it  << " ";
    }

第四种

利用for循环,用索引值访问数据

    for(int i = 0; i < a; i++)
    {
        std::cout << vector[i] << " ";
    }

第五种

利用whlie循环,通过地址访问,耗时最长

    while(it != vector.end())
    {
        std::cout << *it << " ";
        it++;
    }

总结:

  • 使用引用遍历最快,其次是索引访问,最后是地址遍历
  • 耗时时间跟使用循环无关,跟遍历访问获取数据有关
posted @ 2023-09-26 11:42  王白石呦  阅读(354)  评论(0)    收藏  举报