-1

I apologize if this is a duplicate. I promise I tried to find an answer first.

I want to make a binary heap using a vector. To do so, I have to implement a pop function, that removes the "top." In this case, it simply removed the first element.

I tried using a move function, as such:

items[Root()] = std::move(items[cur_size--]);

This should swap the root with another element, which it would then reorder (which also hasn't been working).

Instead, I tried something this:

std::vector<int> items;
int root = 0;
size_t Root() {
  return root;
}

void Pop() {
  items.erase(items.begin()+root);
  root++;
  // here I would call the reorder function
}

In this way I would effectively change the root and operate as if the vector started on the n-th position, rather than at 0.

My question is, does that make sense, or is there a better way I could be implementing this?

edit: added vector

user11344930
  • 49
  • 2
  • 6
  • Why not increasing/decreasing an index instead of moving all the data? – Jose May 17 '19 at 11:02
  • @Jose that's what I'm doing in the second part, moving the root index and erasing the original root – user11344930 May 17 '19 at 11:04
  • 1
    The fragments are a bit small to really understand your problem with the first code. Are you sure you mean `[cur_size--]`? Often with array/vector code, cur_size indicates the element after the end of the array, so the index is wrong before the decriment, so you might mean `[--cur_size]` – Gem Taylor May 17 '19 at 11:11
  • @GemTaylor that solved my problem, thank you! – user11344930 May 17 '19 at 11:21

1 Answers1

2

To pop the first element of an std::vector (lets call it myvector), you just have to write:

myvector.erase(myvector.begin()); // pop front

Now if you have a binary tree stored into a std::vector, removing the root will leave you with the two childs (two roots).

If you want to keep only one of the two sub-trees, you need to select the one you want (the new root).
Then, depending whether your std::vector stores the binary tree in breadth-first or in depth-first, you have to search all the elements relative to the sub-tree you want to keep (Breadth-first search or Depth-first search) and build another std::vector with the desired sub-tree.
In the end, you assign the computed sub-tree to the original vector.


I hope this will help you.

Fareanor
  • 5,900
  • 2
  • 11
  • 37