Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Your task is to reverse the order in which some prints get executed.


Specs:
Your code will be in this form:

//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

You will have to print (or echo, or write, or equivalent) those strings from the fourth to the first.

  • You decide which lines of your program must print the strings, but they must be adjacent;

  • Every line can contain only one print, and cannot exceed 60 bytes in length;

  • Since this is , be creative and avoid to write just a goto or a simple for(i){if(i=4)print"Line1";if(i=3)...}

  • The most upvoted answer in 2 weeks wins this.

  • Your output MUST be Line4 Line3 Line2 Line1 OR Line4Line3Line2Line1 OR Line4\nLine3\nLine2\nLine1(where \n is a newline), and it must be generated only by executing those prints backwards.

Happy coding!

UPDATE: Contest is over! Thank you all :)

share|improve this question
9  
Does Arabic count? : ) –  dimension10 Feb 13 at 8:17
    
If you are able to meet the specs, of course :P –  Vereos Feb 13 at 10:34
    
Wanted to quickly clarify one rule... When you say "Every like can contain only one print", do you mean one text line in the code file or one LOC/statement? –  Ruslan Feb 15 at 8:54
    
Every line of code can contain only one print –  Vereos Feb 15 at 15:07
    
does it have to pass a code review - suitable for production code? –  Lance Feb 17 at 19:37

143 Answers 143

up vote 127 down vote accepted

Commodore 64 BASIC

40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"
share|improve this answer
55  
I never could figure why line numbers are needed, until now. –  ugoren Feb 13 at 9:11
2  
I was going to propose, copying Character ROM ($D000) to RAM ($3000), swapping character bitmaps for "1"<->"4" and "2"<->"3", then running the program in forward order. This is cuter. –  Mark Lakata Feb 14 at 1:08
    
I'm pretty sure you can't actually save/load or otherwise list the code in the order shown using the standard tools (definitely can't on Apple II anyway), all you could do would be type those lines in to the console in that order. And if that's allowed couldn't you just use e.g. C# SendKeys library to type code in any of the answered languages in a different order with arrow keys to move around. –  Lance Feb 19 at 22:55

PHP

Abusing precedence... :-)

!print "Line1\n".
!print "Line2\n".
!print "Line3\n".
!print "Line4\n";
share|improve this answer
2  
In PHP, print may be used as an expression, as it may be in perl, the return value of which is always 1. !1 returns bool(false), which when typed as a string returns the empty string. A more proper restriction for PHP might be to require echo rather than print; the above really is only one statement. –  primo Feb 13 at 6:10
1  
@kuldeep.kamboj It's just grouped that way: print ("Line 1". !print ("Line2". !print ("Line 3". !print "Line4"))); — everything that's on the right of a print statement is part of it. –  bwoebi Feb 13 at 8:18
4  
It seems to work in every version 3v4l.org/dpSpK very impressive! –  eisberg Feb 13 at 13:33
2  
Took me a while to understand (Thanks @eisberg for the link!) but I get it now. While the first print is called first, it doesn't finish evaulating what it needs to print until the inner (lower) prints have already been called and fully evaluated. And the !s are just to hide the 1's that would print otherwise. Brilliant, @bwoebi! –  sfarbota Feb 13 at 17:41
1  
@sfarbota Reading rules is hard. Fixed. Thank you :-) –  bwoebi Feb 13 at 18:38

C (and sort-of Python)

New version, using a macro to fit the question format perfectly. Following Quincunx's comment, I added return to make it nicer.

It also works in Python, but it prints in correct order.

#define print"\n",printf(
#define return"\n"))));}
#define def main(){0?

def main():
    print "Line 1"
    print "Line 2"
    print "Line 3"
    print "Line 4"
    return

main();

Original version - the two are practically the same, after macro substitution:

main(){
    printf("Line 1\n",
    printf("Line 2\n",
    printf("Line 3\n",
    printf("Line 4\n",
    0))));
}
share|improve this answer
1  
+1 for the macro. Maybe include another one; something like #define } 0)))); (I don't know exactly how macros work in C). That way you could just have the print statements in the main method, nothing else. –  Quincunx Feb 13 at 18:55
    
@Quincunx, you can't define }, but you can define return, which I now did. It's almost a polyglot now - the print syntax works in several script languages, #define is often a comment, but main(){..} doesn't work in any language I could find. –  ugoren Feb 13 at 20:44
1  
@Quincunx, and now it's really a polyglot. –  ugoren Feb 13 at 20:50
    
how is the first two defines work without spaces? Would it make print to be replaced by "\n",printf(? –  Lưu Vĩnh Phúc Jun 9 at 11:18
    
@LưuVĩnhPhúc - The space is optional. It replaces as you say. –  ugoren Jun 9 at 12:06

Java

Using reflection

public class ReversePrint {
    public static void main(String[]a) {
        System.out.println("Line1");
        System.out.println("Line2");
        System.out.println("Line3");
        System.out.println("Line4");
    }
    static {
        try{
            Field f=String.class.getDeclaredField("value");
            f.setAccessible(true);
            f.set("Line1","Line4".toCharArray());
            f.set("Line2","Line3".toCharArray());
            f.set("Line3","Line2 ".trim().toCharArray());
            f.set("Line4","Line1 ".trim().toCharArray());
        }catch(Exception e){}
    }
}

Output:

Line4
Line3
Line2
Line1

An explanation of why this works can be found here.

share|improve this answer
51  
Horrible. I like it. –  Roger Lindsjö Feb 12 at 17:20
4  
+1 People always are saying that java Strings are immutable. You prove that they aren't. –  Victor Feb 13 at 4:46
12  
This is delightfully nasty, but the requirement of reverse execution is not met. –  Thorbjørn Ravn Andersen Feb 13 at 9:29
3  
@ThorbjørnRavnAndersen shhhh... your not supposed to tell them that. :p –  Danny Feb 13 at 13:12
4  
@Victor In Java, Strings are immutable. All over Stackoverflow, there are questions like "I thought Strings were immutable". They use reflection and it makes them seem immutable. Java's promises work like this: "If you use our things / classes in the way we intended, then we promise that our claims are correct." Reflection is not the way classes are intended to use. –  Quincunx Feb 15 at 19:37

C

Undefined behavior is the most exciting kind of behavior!

f(){}
main()
{
   f(printf("Line 1\n"), 
     printf("Line 2\n"), 
     printf("Line 3\n"), 
     printf("Line 4\n"));
}

Actual output may vary depending on your compiler, linker, operating system, and processor :)

share|improve this answer
13  
I have absolutely no idea how come this actually works, +1. –  svick Feb 12 at 18:39
5  
@svick: to support varargs, most C compilers put function arguments on the stack in reverse order (so the top item on the stack is always the 1st argument), which means they're likely to evaluate arguments in the same way. Of course, this assumes arguments are passed on the stack which becomes less and less the case with newer compilers. –  Guntram Blohm Feb 12 at 21:53
    
As @GuntramBlohm said, the basic idea is that C function parameters are often (but not always) pushed onto the stack in a right-to-left order. Since these are function calls, the functions are probably (but not necessarily) called from right-to-left as well. All this is not defined by the C standard though, so while it happens to yield the right result in GCC 4 it's totally up to the compiler and calling convention what actually happens. –  Nick Feb 13 at 21:21
1  
@fluffy: Alas, it is the other way around: C does not treat arglist commas as sequence points, unlike other commas. –  Williham Totland Feb 14 at 15:08
4  
@WillihamTotland well then I know of some code that I really need to fix... thanks –  fluffy Feb 14 at 23:12

Ruby

print 'Line1' unless
print 'Line2' unless
print 'Line3' unless
print 'Line4'

Edit: Alternatively,

def method_missing(meth,*)
  puts meth.to_s.sub('print'){}
end

printLine1(
printLine2(
printLine3(
printLine4)))
share|improve this answer
24  
I prefer this because it has meth –  DebugErr Feb 12 at 14:47
1  
Wouldn't you normaly post two answers if you had two solutions? –  TheConstructor Feb 12 at 15:30
3  
Wouldn't this look more ruby-ish with code blocks? pastebin.com/LDWpxKx8 –  manatwork Feb 12 at 15:37
2  
@PacMani those parens don't use white space, they use White space. –  corsiKa Feb 12 at 18:22
    
@manatwork nice one! I do think method_missing is pretty Ruby-ish itself, though. –  histocrat Feb 12 at 22:14

C

main()
{
  int i = 0;
  for(; i == 0; printf("Line 1\n"))
    for(; i == 0; printf("Line 2\n"))
      for(; i == 0; printf("Line 3\n"))
        for(; i == 0; printf("Line 4\n"))
          i = 1;
}
share|improve this answer

PHP

I know, this is madness...

goto d;
a: print "Line1\n"; goto end;
b: print "Line2\n"; goto a;
c: print "Line3\n"; goto b;
d: print "Line4\n"; goto c;
end: exit;
share|improve this answer
56  
That noise you hear is Dijkstra spinning in his grave. :-) –  Gareth Feb 12 at 12:21
20  
Thought somebody said "be creative and avoid to write just a goto" ;-) –  TheConstructor Feb 12 at 15:29
18  
@TheConstructor The creative part is using goto in PHP ;) –  NikiC Feb 12 at 18:54
    
So full of win. –  Nick T Feb 12 at 20:36

ES6 (using backwards mode ;)

Wow, it looks like the designers of ECMAScript had some incredible foresight when they made backwards mode part of the spec:

// activate backwards mode:
'use backwardsˈ; \* mode backwards in now *\
code of lines some ⧵\
\*code*\ "Line1" print \*code*\
\*code*\ "Line2" print \*code*\
\*code*\ "Line3" print \*code*\
\*code*\ "Line4" print \*code*\
code of lines some ⧵\
⁏ˈforwards useˈ // back to ˈnormal'.

// So simple! No need to do anything this complicated:
split('"').reduce((L,o,l)=>(l%2?o:'')+L,'')

Output (evaluation, really):

"Line4Line3Line2Line1"

Note that it's exactly of the form requested, with only slight backwardification to fit the syntax of the mode. Note also that this mode is only supported in recent versions of Firefox at the moment.

Final note: Actually, there is no backwards mode. But this is still a valid script that runs in Firefox (copy the whole thing). :D

share|improve this answer
4  
All 3 links you posted are leading to 404. Is this kind of joke? –  manatwork Feb 13 at 13:04
6  
Ah. I see now. The syntax highlighter was your accomplice here. –  manatwork Feb 13 at 14:34
9  
This is a combo popularity-contest and code-trolling, no? :) I love it. –  Not that Charles Feb 14 at 15:55
5  
This is a phenomenal abuse of Javascript. I like it. –  Seiyria Feb 14 at 16:11
2  
Sneaky. Soooo sneaky.... –  David Conrad Feb 18 at 19:37

Haskell

This is almost idiomatic Haskell, as the program now looks like a right-to-left function composition. If the function wasn't print, but something that would return a (useful) value the operator declaration would be unnecessary and the code would be something you'd see in libraries.

a << b = (const a =<< b)

main = putStrLn "Line1"
    << putStrLn "Line2"
    << putStrLn "Line3"
    << putStrLn "Line4"
share|improve this answer
4  
tip: (<<) = flip (>>) –  Bergi Feb 12 at 20:26
    
@Bergi That's another way to write it, I guess a little more elegant even. I was actually a little surprised to see the thing wasn't defined in prelude (or Control.Monad) –  shiona Feb 12 at 23:50
    
@shiona:Yeah, it's a surprising thing to miss. Happily, we have both operators for Applicatives: <* and *>. –  Tikhon Jelvis Feb 13 at 12:42

Perl

use threads;

$a=threads->create(sub {sleep(5); print("Line1\n");});
$b=threads->create(sub {sleep(4); print("Line2\n");});
$c=threads->create(sub {sleep(3); print("Line3\n");});
$d=threads->create(sub {sleep(2); print("Line4\n");});

$a->join();
$b->join();
$c->join();
$d->join();
share|improve this answer
1  
+1, I like this one –  Florent Feb 12 at 12:21
15  
This is theoretically not guaranteed to print in exact reverse order. –  Cruncher Feb 12 at 16:12
2  
@Cruncher I know, but with 1 second gaps the chances of it printing in anything other than reverse order are pretty slim. –  Gareth Feb 12 at 16:13
2  
@Gareth That's why I italicized theoretically :) –  Cruncher Feb 12 at 16:20
    
@Cruncher Isn't that what makes it so fun? –  Pierre Arlaud Feb 17 at 9:37

HTML + CSS

<p>Line 1</p>
<p>Line 2</p>
<p>Line 3</p>
<p>Line 4</p>

CSS:

body {margin-top:7em}
p + p {margin-top:-4em}

See jsFiddle.

Edit:
To conform to the rules better, here is a variant in XML, that actually uses print.

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="style.css"?>
<root>
  <print>Line 1</print>
  <print>Line 2</print>
  <print>Line 3</print>
  <print>Line 4</print>
</root>

where style.css should be

* {display:block; margin-top:3em}
print + print {margin-top:-3em}

HTML without CSS

And for the heck of it, here's one without CSS.

<table>
<tfoot><tr><td><table><tfoot><tr><td>Line 1</tr></tfoot>
<tbody><tr><td>                      Line 2</table></tfoot>
<tbody><tr><td><table><tfoot><tr><td>Line 3</tr></tfoot>
<tbody><tr><td>                      Line 4</table></tbody>
</table>

Fiddle.

share|improve this answer
2  
Can anybody explain the downvote? This does work when printing, you know. –  Mr Lister Feb 14 at 12:42
    
You can also just do p {float:right;} –  Noyo Feb 14 at 12:52
    
But then the results will all be on one line! –  Mr Lister Feb 14 at 12:57
    
...and that's allowed. :] –  Noyo Feb 14 at 14:25
1  
...and that's not disallowed. :D You could also wrap it in a div and add the CSS rule div {float:left}. –  Noyo Feb 14 at 15:05

Haskell

main = sequence_ $ reverse [
    putStr "Line1",
    putStr "Line2",
    putStr "Line3",
    putStr "Line4"]
share|improve this answer

Javascript

setTimeout(function(){console.log("Line 1");},900);
setTimeout(function(){console.log("Line 2");},800);
setTimeout(function(){console.log("Line 3");},700);
setTimeout(function(){console.log("Line 4");},600);
share|improve this answer
    
Using 1,2,3,4 as timeouts also works for me. (However, I do not know whether this behavior is standardized in ECMAScript.) –  ComFreek Feb 12 at 20:06
1  
@ComFreek: setTimeout is standardized in HTML5/timers, not in ES. Also, it specifies a minimum timeout of 4ms :-) –  Bergi Feb 12 at 20:32
1  
@Bergi Yep, you are right, of course! HTML Standard - Timers - if anyone is interested. –  ComFreek Feb 12 at 20:46
    
Run this on a slow enough machine (say, an 8086 running several other applications?) and it will fail. (By fail, I mean the order will not be reversed, since it will take >= 100ms to execute each statement. –  Jeff Davis Feb 13 at 22:20
    
@JeffDavis No it won't. See jsfiddle.net/wM5em –  lastr2d2 Feb 14 at 5:23

C++

#include <iostream>
#define Q(x,y) x ## y
#define P(x,y) Q(x, y)
#define print S P(s, __LINE__) =
struct S { const char *s; S(const char *s): s(s) {} ~S() { std::cout << s << std::endl; } };
int main() {
    print "Line1";
    print "Line2";
    print "Line3";
    print "Line4";
}

(Local variables are destroyed in reverse order of declaration.)

C++11

#include <iostream>
int main() {
    struct S { void (*f)(); S(void (*f)()): f(f) {} ~S() { f(); } } s[] = {
        {[](){ std::cout << "Line1" << std::endl; }},
        {[](){ std::cout << "Line2" << std::endl; }},
        {[](){ std::cout << "Line3" << std::endl; }},
        {[](){ std::cout << "Line4" << std::endl; }},
    };
}

(Much the same, but using lambdas and an array data member instead.)

share|improve this answer

Brainfuck

Assumes cell-wrapping.

++++[->+
----[> (line 1) .[-]<]++++
---[> (line 2) .[-]<]+++
--[> (line 3) .[-]<]++
-[> (line 4) .[-]<]+
<]

Why it works

The first and last lines compose of a loop that repeats four times (counter = cell0).

Inside the loop, there is a counter variable (cell1) that is increased every run.

Each lines checks if decreasing by four, three, two, or one equals zero. Therefore, on the first run, the counter is one and the last line is executed, on the second run, the third line is executed, etc.

The (line 1) shows where you should make the text that is printed. The arrows in the loops allocate cell2 for this purpose. The [-] cleans out cell2 after you use it.

share|improve this answer

Java

import java.io.PrintStream;
import java.util.concurrent.FutureTask;

public class Print {
  public static void main(String[] args) {
    new FutureTask<PrintStream>(new Runnable() {
      public void run() {
        new FutureTask<PrintStream>(new Runnable() {
          public void run() {
            new FutureTask<PrintStream>(new Runnable() {
              public void run() {
                System.out.append("Line1"); }
            }, System.out.append("Line2")).run(); }
        }, System.out.append("Line3")).run(); }
    }, System.out.append("Line4")).run();
  }
}

It's all in the right timing... ;-)

share|improve this answer
    
The lines have to be adjacent. –  Timtech Feb 12 at 15:09
    
They are no less adjacent than e.g. with codegolf.stackexchange.com/a/20660/16293 nobody said they should look the same. Will remove some newline-characters ;-) –  TheConstructor Feb 12 at 15:13
    
Okay, great :-) –  Timtech Feb 12 at 15:14

Python 3

import atexit

atexit.register(print,"Line1")
atexit.register(print,"Line2")
atexit.register(print,"Line3")
atexit.register(print,"Line4")
share|improve this answer

C

Trying to make defiance of the tips in the question as creative as possible:

#include <stdio.h>
#define print if (i == __LINE__) puts
static unsigned i;
int main(void) {
  while (--i) {
    print("Line 1");
    print("Line 2");
    print("Line 3");
    print("Line 4");
  }
  return 0;
}
share|improve this answer
3  
nice abuse of a #define :P +1 –  masterX244 Feb 13 at 16:25

PHP

Another eval variant:

$lines=array_slice(file(__FILE__),-4); // get last 4 lines of current file
eval(implode('',array_reverse($lines)));exit; // eval lines reversed and exit
print "Line1\n";
print "Line2\n";
print "Line3\n";
print "Line4\n";
share|improve this answer
1  
Slick! Nonetheless, I feel compelled to point out this is a really bad idea. –  David Kryzaniak Feb 12 at 22:53

Bash

In memory of the revered SleepSort and SleepAdd, I present to you... SleepReverse:

#!/bin/bash

function print(){(sleep $((4-$1));echo "Line $1";)&}

print 1
print 2
print 3
print 4
share|improve this answer
    
For it to look more like the specs, use $1 and $2: function print(){(sleep $((4-$2));echo "$1 $2";)&}; print Line 1 –  plg Feb 25 at 19:35

Common Lisp № 1

It's easy to write a ngorp macro that executes its forms in reverse order:

(macrolet ((ngorp (&body ydob) `(progn ,@(reverse ydob))))
  (ngorp
   (write-line "Line 1")
   (write-line "Line 2")
   (write-line "Line 3")
   (write-line "Line 4")))
Line 4
Line 3
Line 2
Line 1

Common Lisp № 2

Here's one that takes the problem very literally; the code from the question appears in program without modification:

(macrolet ((execute-prints-backwards (&body body)
             `(progn 
                ,@(nreverse (mapcar (lambda (string)
                                      (list 'write-line string))
                                    (remove-if-not 'stringp body))))))
  (execute-prints-backwards

//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

  ))
Line4
Line3
Line2
Line1
share|improve this answer

Bash

Here comes the double-faced script:

#!/bin/bash
s=1
if [ $s -ne 0 ]; then tac $0 | bash; exit; fi
s=0
echo "Line1"
echo "Line2"
echo "Line3"
echo "Line4"
share|improve this answer
1  
I never even knew tac existed! Haha, thanks. –  Noyo Feb 14 at 10:25

Python3

print("Line1",
print("Line2",
print("Line3",
print("Line4") or '') or '') or '')

Can be 6 bytes shorter by removing all spaces in last line.

share|improve this answer

Batch

echo off

call :revers ^
echo.line1 ^
echo.line2 ^
echo.line3 ^
echo.line4

:revers
if not "%2"=="" call :revers %2 %3 %4 %5 %6 %7 %8 %9
%1
share|improve this answer
    
Welcome to codegolf! Nice post. –  Cruncher Feb 13 at 16:33

C#

Instead of directly calling the Run method, I'm creating a dynamic method that contains a copy of Run's IL bytecode, except that the load-string opcode operands are swapped. Which causes the new method to display the strings in reverse order.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace TestApp
{
    class Program
    {
        public static void Run()
        {
            Console.WriteLine("Line 1");
            Console.WriteLine("Line 2");
            Console.WriteLine("Line 3");
            Console.WriteLine("Line 4");
        }


        static void Main(string[] args)
        {
            var method = typeof(Program).GetMethod("Run");
            var il = method.GetMethodBody().GetILAsByteArray();
            var loadStringOperands = new Stack<int>();
            for (int i = 0; i < il.Length; i++)
            {
                if (il[i] == OpCodes.Ldstr.Value)
                {
                    loadStringOperands.Push(BitConverter.ToInt32(il, i + 1));
                    i += 4;
                }
            }

            var run = new DynamicMethod("Run", typeof(void), null);
            var gen = run.GetILGenerator(il.Length);
            for (int i = 0; i < il.Length; i++)
            {
                if (il[i] == OpCodes.Ldstr.Value)
                {
                    var str = method.Module.ResolveString(loadStringOperands.Pop());
                    gen.Emit(OpCodes.Ldstr, str);
                    i += 4;
                }
                else if (il[i] == OpCodes.Call.Value)
                {
                    var mInfo = method.Module.ResolveMethod(BitConverter.ToInt32(il, i + 1)) as MethodInfo;
                    gen.Emit(OpCodes.Call, mInfo);
                    i += 4;
                }
                else if (il[i] == OpCodes.Ret.Value)
                {
                    gen.Emit(OpCodes.Ret);
                }
            }

            run.Invoke(null, null);
        }
    }
}
share|improve this answer

F#

let inline (?) f g x = g x; f x

(printfn "Line1%s") ?
 (printfn "Line2%s") ?
  (printfn "Line3%s") ?
   (printfn "Line4%s") ""

Just created a custom operator that executes functions in reverse order.

share|improve this answer
3  
I am pretty sure (?) f(g(x)) = g(x); f(x) is calculus and not programming. –  Jeff Davis Feb 13 at 22:27
    
@JeffDavis: Pretty sure (?) f g x reads roughly as (?)(f, g, x), not f(g(x)) –  Eric Feb 17 at 0:41

Python

yet another solution using eval()

a = [
"print('Line1')",
"print('Line2')",
"print('Line3')",
"print('Line4')"]

for line in reversed(a):
    eval(line)

it's not very complex, but easy to understand.

share|improve this answer
1  
the only code I understand :D –  moldovean Feb 13 at 8:31

Go (Golang)

package main

import "fmt"

func main() {
    defer fmt.Println("Line 1")
    defer fmt.Println("Line 2")
    defer fmt.Println("Line 3")
    defer fmt.Println("Line 4")
}

Try it out: http://play.golang.org/p/fjsJLwOFn2

share|improve this answer
    
I wanted to post the exact same code. Literally, byte-for-byte exactly the same. –  Art Feb 13 at 15:08
    
@Art, awesome! I hope to see more Go used in Code Golf. –  cory.todd Feb 13 at 19:18
    
Probably won't happen. Go isn't really good a being compressed, they deliberately limit weird constructs so that you can't create an unreadable mess. But in this case (and maybe other popularity contests) it has a chance. –  Art Feb 14 at 8:40

Javascript

[
  "console.log('Line1')",
  "console.log('Line2')",
  "console.log('Line3')",
  "console.log('Line4')"
].reverse().forEach(function(e){eval(e)})

C++11

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::function<void()>> functors;
    functors.push_back([] { std::cout << "Line1"; });
    functors.push_back([] { std::cout << "Line2"; });
    functors.push_back([] { std::cout << "Line3"; });
    functors.push_back([] { std::cout << "Line4"; });
    std::reverse(functors.begin(),functors.end());
    std::for_each (functors.begin(), functors.end(), [](std::function<void()> f) {f();});
    return 0;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.