title: How to check if a range specified by iterators is valid?
body: <p>Many of the standard library containers have operations that accept a range specified by iterators. For example, <code>std::list::assign(InputIterator first, InputIterator last)</code>.</p>
  
  <p>But because many of these operations do not throw exceptions, if the range specified by <code>[first,last)</code> is not valid, it will cause undefined behaviour.</p>
  
  <p>So what <em>is</em> a valid range? I assume it means that <code>first</code> comes before or is equal to <code>last</code> in the container, because when I tried otherwise (i.e. <code>first</code> comes after <code>last</code>), the program's execution would hang.</p>
  
  <p>For example:</p>
  
  <pre><code>std::list.assign(container.begin(), container.end()); // valid range
  std::list.assign(container.end(), container.begin()); // invalid range
  </code></pre>
  
  <p>Now with an assumption of what a valid range is, how can we check if a range is valid?</p>
  
  <p>I came up with a helper function that checks if <code>first</code> is ever equal to <code>last</code> before it reaches the end of the container. If true, it's a strong guarantee that <code>first</code> does not come after <code>last</code> and therefore the range is valid.</p>
  
  <pre><code>template &lt;typename Iterator&gt;
  bool isValidRange(Iterator first, Iterator last, Iterator end)
  {
    for (; first != end; ++first)
      if (first == last) return true;
    return false;
  }
  </code></pre>
  
  <p>It's not very convenient because you have to pass it an iterator to the end of the container in addition to the iterators that specify the range.</p>
  
  <p>Is this correct? Is there a better way to do this?</p>