OK, since I now (think I) understand what your code is about, here's my take on it:
auto iter = v.begin();
auto end = v.end();
while (iter != end && iter->empty())
++iter;
if (iter != end)
{
while (true) // loop and a half
{
auto next = iter+1; // at this point, we know iter != end
while (next != end && next->empty())
++next;
if (next == end)
break;
auto lhslast = lhs.end();
--lhslast;
if (lhslast->first > next->begin()->first)
throw std::runtime_error("invalid key order");
iter = next;
}
}
Edit:
The code above can be further improved using another algorithm:
Replace
while (iter != end && iter->empty())
++iter;
with
iter = std::find_if(iter, end,
[](std::map<double, double> const& m) { return m.empty(); });
and analogous for the next
loop.
Another option is to notice that if it were not empty maps, you could just use adjacent_find
. Therefore another option is to make use of Boost's filter_iterator
to get rid of the empty maps. Thus do
#include <boost/iterator/filter_iterator.hpp>
struct is_not_empty
{
template<typename Container> bool operator()(Container const& c) const
{
return !c.empty();
}
};
and then at the place of your code
auto fbegin = boost::make_filter_iterator(is_not_empty(), v.begin(), v.end());
auto fend = boost::make_filter_iterator(is_not_empty(), v.end(), v.end());
if (std::adjacent_find(fbegin, fend,
[](std::map<double, double> const& lhs,
std::map<double, double> const& rhs) -> bool
{
auto lhslast = lhs.end();
--lhslast;
return lhslast->first > rhs.begin()->first;
}) != fend)
throw std::runtime_error("invalid key order");
The filter iterator makes sure that only the non-empty maps are considered.