Create a gist now

Instantly share code, notes, and snippets.

@thiagomg /loop2.cpp
Last active Oct 13, 2015

Embed
What would you like to do?
Range loops - Writing safe
//Positive end means [start:start+end)
//Negative end means [start:size-end)
template<typename T>
range<T> narrow_range(const T &cont, int start, int end) {
int items = std::distance(cont.cbegin(), cont.cend());
if( items == 0 || end == 0 ) //Checking for empty range
return range<T>(cont.cend(), cont.cend());
/*
Some other checkings stripped to make it less verbose
*/
if( end > 0 ) {
return range<T>(cont.cbegin()+start, cont.cbegin()+start+end);
} else
return range<T>(cont.cbegin()+start, cont.cend()+end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment