Skip to content

Instantly share code, notes, and snippets.

@thiagomg
Last active October 13, 2015 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagomg/b863b666c01d6ea26e56 to your computer and use it in GitHub Desktop.
Save thiagomg/b863b666c01d6ea26e56 to your computer and use it in GitHub Desktop.
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