views:

1156

answers:

3

Given the code below, how would you create/implement SR.h so that it produces the correct output WITHOUT any asterisks in your solution?

I got bummed by this question. I would like to know some of the different approaches that people use for this problem.

#include <cstdio>
#include "SR.h"

int main()
{
    int j = 5;
    int a[] = {10, 15};
    {
        SR x(j), y(a[0]), z(a[1]);

        j = a[0];
        a[0] = a[1];
        a[1] = j;

        printf("j = %d, a = {%d, %d}\n", j, a[0], a[1]);
    }

    printf("j = %d, a = {%d, %d}\n", j, a[0], a[1]);
}

output

j = 10, a = {15, 10}
j = 5, a = {10, 15}

Second one:

#include <cstdio>
#include "SR.h"
int main()
{
    int sum = 0;
    for (int i = 1; i < 100; i++) {
        SR ii(i);
        while (i--)
            sum += i;
    }
    printf("sum = %d\n", sum);
}

//The output is "sum = 161700".
+8  A: 

I don't have time to write code but, you need to use references &int in constructor. And you would need to restore original values to references in the destructor. When SR goes out of scope it needs to restore original values that were passed in during construction.

Kugel
+1 Cool and Crisp!
Bragboy
+41  A: 

SR is acting as a captured-variable-restorer. When it goes out of scope it restores some value that it previously captured.

The constructor will do two things: capture a reference, and capture the value of that reference. The destructor will restore the original value to that reference.

class SR
{
public:
  SR(int& var) : capture(var), value(var) {}
  ~SR() { capture = value; }

private:
  int& capture;
  int value;
};

Edit: Just a guess, but I assume SR is supposed to stand for ScopeRestorer?

Bill
My thought was SR = SaveRestore.
Mark Ransom
@Mark: SaveRestore seems a lot more likely, thanks!
Bill
+1  A: 

For the first one:

class SR
{
    int &ref;
    int orig;
public:
    SR(int& r)
    :ref(r), orig(r)
    {
    }

    ~SR()
    {
        ref = orig;
    } 
};

For the second snippet, should it be the same SR or some other SR?

Seva Alekseyev
This solution works for both, so I assume it's meant to satisfy both `main` functions.
Bill
yes...it's meant for both
EquinoX
Your code wont compile until you place a colon after public
Beh Tou Cheh
Sorry, typo. Fixed.
Seva Alekseyev