0

I am trying to copy a binary tree in a c++ vector and i am having a kind of error that I cant find where it is generated. This i in the header file (.h)

struct NyjePeme
{
  int Key;
  NyjePeme *left = NULL;
  NyjePeme *right = NULL;
};
class PemeKerkimi
{
  private:
  NyjePeme *root;

public:
  PemeKerkimi();
  ~PemeKerkimi();

And there are the methods i have used in .cpp file:

void ASCVektor(vector<int> v)
{
  int i, j;
  for (i = 0; i < v.size() - 1; i++)
{
    for (j = i + 1; j < v.size(); j++)
    {
        if (v[i] > v[j])
        {
            int tmp = v[i];
            v[i] = v[j];
            v[j] = tmp;
        }
    }
   }
}

void printVektor(vector<int> v)
{
  int i;
  for (i = 0; i < v.size(); i++)
  {
    cout << v[i] << ", ";
  }
  cout << endl;
}

void copyTreeinVector(NyjePeme *T, vector<int> v)
{

  if (T != NULL)
  {
    copyTreeinVector(T->left, v);
    v.push_back(T->Key);
    copyTreeinVector(T->right, v);
    return;
  }
  return;
}

NyjePeme *PemeKerkimi::TheKSmallestElement(int k)
{
   vector<int> v;
   coptyTreeinVector(root, v);
   ASCVektor(v);
...
   

The problem is in copyTreeinVector() function and the error message is this:

Process returned -1073741819 (0xC0000005) and it takes a while to throw that message. I searched about that error and it is generated due to bad use of pointers... but I cant find the problem in my code

ALB_DEV
  • 13
  • 5
  • PemeKerkimi = BinaryTree NyjePeme = Node Just forgot to translate :) – ALB_DEV May 29 '21 at 23:11
  • 3
    Please present this as a [mre]. It is not possible to answer your question as posted. – Paul Sanders May 29 '21 at 23:19
  • 2
    You're passing your vector to your functions by value. That means whatever vector in main you're trying to copy your data into is not the same vector that exists in your function. Pass by reference instead. `std::vector& v`. – JohnFilleau May 29 '21 at 23:30

1 Answers1

1

You should pass vector in copyTreeinVector function by-reference.

Instead of writing

void copyTreeinVector(NyjePeme *T, vector<int> v)

You should have written

void copyTreeinVector(NyjePeme *T, vector<int>& v)

Here are some additional links related to the issue.

What's the difference between passing by reference vs. passing by value? https://www.educative.io/edpresso/pass-by-value-vs-pass-by-reference

Karen Baghdasaryan
  • 2,407
  • 6
  • 24
  • @KlodjanMata Note that C++ is a value-based language, not a reference based language. If you are familiar with languages that automatically pass objects by reference (java, C#, etc.), then that may be the reason why you made the error for C++. – PaulMcKenzie May 30 '21 at 01:09