Caduchon
Caduchon

Reputation: 5201

Check if an iterator precedes another one

I would like to check if an iterator (or similar types) precedes another one. In this example, I would like to check I don't have an infinite loop. It means, "if I apply operator ++ enough times on begin, I arrive to end". Is it possible in C++98 ? Maybe with restriction on the type T ?

/**
 * \brief Loop
 * \attention T must implement operator++() and operator!=(const T&)
 * \param begin Begin of the loop
 * \param end End of the loop
 * \pre begin precedes end
 */
template <typename T>
void loop(const T& begin, const T& end)
{
  T run = begin;
  while(run != end)
  {
    /* do something with run */
    ++run;
  }
}

loop(0,10);

std::set<double> x;
x.insert(1.0);
x.insert(2.0);
x.insert(3.0);
loop(x.begin(), x.end());

Upvotes: 4

Views: 1017

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

If you have random access iterators, such as you would get from a std::vector, std::basic_string, std::deque or std::array, and you know they are from the same container, then you can compare them with operator< (or any of the other relational operators). Otherwise, you need to document your function's behavior and count on the user to pass valid iterators that meet the criteria.

Upvotes: 7

Related Questions