Skip to content

Instantly share code, notes, and snippets.

@sguzman
Created March 4, 2014 06:41
Show Gist options
  • Save sguzman/9341432 to your computer and use it in GitHub Desktop.
Save sguzman/9341432 to your computer and use it in GitHub Desktop.
How to print a list with spaces inserted inbetween without worrying about adding extra spaces at the end or checking for a one time condition for all iterations
#include <iostream>
#include <functional>
int main(int argc, char *argv[])
{
auto printHead = [] (int num)
{
std::cout << num;
};
auto printTail = [] (int num)
{
std::cout << ' ' << num;
};
// Need explicit type for lambda if its going to be captured
std::function<void(int)> print = [&printHead, &printTail, &print] (int num)
{
printHead(num);
print = printTail;
};
for (auto& element : {1,2,3,4,5,6,6,7,8,9,6})
{
print(element);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment