Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an iterator precedes another one

Tags:

c++

iterator

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());
like image 546
Caduchon Avatar asked Mar 18 '23 05:03

Caduchon


1 Answers

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.

like image 159
Benjamin Lindley Avatar answered Apr 02 '23 17:04

Benjamin Lindley