1

Say I have a struct:

struct TrieNode {
const NumChars = 26;
bool isWord;
int letterCount;
TrieNode *letters[NumChars];

TrieNode() {
    isWord = false;
    for ( int i = 0; i < NumChars; i += 1 ) {
        letters[i] = NULL;
    } // for
    letterCount = 0;
 }
};

I create a TrieNode on the heap like this:

TrieNode *root = new TrieNode();

Now how can I create a different copy of root? (deep copy)

thisiscrazy4
  • 1,905
  • 8
  • 35
  • 58

3 Answers3

4

In C++ you can do this be defining a custom "copy constructor". It would be of the form:

TrieNode(const TrieNode& copyFrom){
  //Do the copying here
}

Then you can use this pretty much anyway you want:

TrieNode example;
TrieNode deep(example);
TrieNode deep2 = example;

If you want to define a copy constructor, chances are you'll also want to define a destructor and an assignment operator. This is called the Rule of 3.

If you implement the assignment operator (=) then you can also write code like:

TrieNode example;
TrieNode deep;
//Do stuff
deep = example; //Still a deep copy.
Community
  • 1
  • 1
daniel gratzer
  • 52,833
  • 11
  • 94
  • 134
2

You write a recursive routine to do the copy. I.e. a routine that copies isWord and letterCount and then calls itself recursively on each non-NULL element of letters. You can make this routine a copy constructor or not. Whatever makes most sense for the rest of your code.

john
  • 85,011
  • 4
  • 57
  • 81
2
struct TrieNode {
   static const NumChars = 26;
   bool isWord;
   int letterCount;
   TrieNode *letters[NumChars];

   TrieNode() : isWord(false), letterCount(0) {
      for ( int i = 0; i < NumChars; i += 1 ) {
         letters[i] = NULL;
      } // for
   }
   TrieNode(const TrieNode &other)
       : isWord(other.isWord), letterCount(other.letterCount)
   {
      for ( int i = 0; i < NumChars; ++i ) {
         if (other.letters[i]) {
            letters[i] = new TrieNode(other.letters[i]);
         } else {
            letters[i] = NULL;
         }
      }
   }
};


TrieNode *root = new TrieNode();
TrieNode *deepcopy = new TrieNode(*root);

It's a recursive data structure, so you need a recursive copying algorithm. Notice how the copy constructor I made calls itself to create the sub-nodes?

IMHO, the thing has several design flaws. But you didn't ask to fix them, you just asked how to make a deep copy of it.

Omnifarious
  • 54,333
  • 19
  • 131
  • 194