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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With