std :: merge如何在C ++中工作?

时间:2015-03-21 21:37:59

标签: c++ stl merge

下面是直接从C ++中std :: merge的链接(在末尾给出)中获取的代码。我理解在while循环(复制部分)中发生了什么,但我不明白这个循环何时结束。因为while (true)这个循环不能永远运行吗?

template <class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator 
  merge (InputIterator1 first1, InputIterator1 last1, 
         InputIterator2 first2, InputIterator2 last2, 
         OutputIterator result)
{   
    while (true) {
        if (first1==last1) return std::copy(first2,last2,result);
        if (first2==last2) return std::copy(first1,last1,result);
        *result++ = (*first2<*first1)? *first2++ : *first1++;   
    } 
}

http://www.cplusplus.com/reference/algorithm/merge/

2 个答案:

答案 0 :(得分:4)

在每次迭代中,first1first2都会递增,因此在某些时候,其中一个将分别等于last1last2(前提是指定了参数正确),因此将执行return个语句之一。

答案 1 :(得分:1)

退出循环有两种方法:

  1. 继续条件变为false。显然,这不会发生,因为文字true永远不会变为假。

  2. 从循环内部到某个外部位置的分支。可以执行此操作的语句包括breakreturngotothrow,对longjmpexit函数的调用等。代码在循环中有两个return语句。