Last active
October 13, 2015 01:28
-
-
Save thiagomg/b863b666c01d6ea26e56 to your computer and use it in GitHub Desktop.
Range loops - Writing safe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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