Speed accessing a std::vector by iterator vs by operator[]/index?

后端 未结 11 890
刺人心
刺人心 2020-12-03 04:42

Say, I have a

std::vector v;

in my code and I need to access its elements very often in the program, looping them forwa

11条回答
  •  广开言路
    2020-12-03 05:00

    I had a test yesterday, use [] vs iterator, the code is create a vector with some elements and remove some elements from the vector. This is the code uses operator [] to access elements

      TimeSpent([](){
        std::vector vt = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
        for (int i = int(vt.size()) - 1; i >= 0; i--)
        {
          if (vt[i] % 2 == 0)
          {
            //cout << "removing " << vt[i] << endl;
            vt.erase(vt.begin() + i);
          }
        }
      });
    

    The following code is about access vector elements by using iterator

      TimeSpent([](){
        std::vector vt = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
        for (std::vector::iterator num = vt.begin(); num != vt.end();)
        {
          if (*num % 2 == 0)
          {
            num = vt.erase(num);
          }
          else
          {
            ++num;
          }
        }
      });
    

    Tested by calling them by this function separately

    void TimeSpent(std::function func)
    {
      const int ONE_MIL = 10000;
      long times = ONE_MIL;
      std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
      while (times > 0)
      {
        func();
        --times;
      }
      std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
      cout << "time elapsed : " << std::chrono::duration_cast(end - start).count() << endl;
    }
    


    Tested environment is visual studio 2013 pro. version 4.5.51650
    The results are :
    operator[] : 192
    iterator : 212
    Summary: when we access the vector container, operator [] is faster than iterator.

提交回复
热议问题