tags:

views:

79

answers:

1

Hi Guys,

a bit of a vague question but I am looking for pointers as to how can I generate String diff vectors in C++. The scenario is such that given a paragraph I want to store the various differences(Edit, cut copy paste etc.) it goes through in a draft mode to review Audit history.

Any hints in this regard will be really appreciated.

+4  A: 

An idea using C++ polymorphism:

class Action
{
    public:
    virtual void revert(std::string& base) = 0;
};

class InsertAction : public Action
{
    private:
    int pos, len;
    public:
    InsertAction(int pos, std::string& base, const std::string& in) : len(in.size()), pos(pos)
    {
        base.insert(pos, in);
    }

    virtual void revert(std::string& base)
    {
        base.erase(pos,len);
    }
};

int main()
{
    std::string text("hello !");
    std::cout << text << std::endl;
    Action* action = new InsertAction(5, text, " world");
    std::cout << text << std::endl;
    action->revert(text);
    std::cout << text << std::endl;
    delete action;
}

You can then add and pop Actions from a LIFO queue as you want. It's a simple example, you could also try to link it more to a string instead of always passing at as a param, but that's up to your own design. I know it's not 'real' diffing, but I think this solution to be closer coupled to the problem then really storing general string differences.

KillianDS
MSalters
+1 I like that.
Konrad
I always thought of this pattern that the `revert()` member would return an `Action`, too? `InsertAction` would return an `EraseAction` etc. (I'm not sure about the benefits/drawbacks of one way vs. the other, it's just that I never thought of it this way.) Anyway, +1 from me.
sbi
Thanks, a good start :) appreciate it
SWKK