How do you find the iterator in the middle of two iterators?

前端 未结 4 724
自闭症患者
自闭症患者 2021-01-17 12:51

I\'m trying to convert my implementation of quicksort into a template that can be used with other containers besides a vector.

Originally I used indexes to find the

相关标签:
4条回答
  • 2021-01-17 13:23

    use:

    http://www.cplusplus.com/reference/std/iterator/distance/

    and

    http://www.cplusplus.com/reference/std/iterator/advance/

    0 讨论(0)
  • 2021-01-17 13:36

    std::distance can measure the distance between two iterators as efficiently as possible.

    std::advance can increment an iterator as efficiently as possible.

    I still wouldn't want to quicksort a linked list, though :)

    0 讨论(0)
  • 2021-01-17 13:44

    To find middle iterator you should use:

    first + (last - first) / 2
    
    0 讨论(0)
  • 2021-01-17 13:47

    How about something like this?

    bool isMovingFirst = true;
    while(first != last) {
      if(isMovingFirst) {
        ++first;
      } else {
        --last;
      }
      isMovingFirst = !isMovingFirst;
    }
    
    0 讨论(0)
提交回复
热议问题