-1

I'm solving a problem with the segment tree. It has got a very strict memory limit, so I don't want to use extra n memory for remembering information about single segments and return it from the array I built the tree from.

...
struct SegTree {
    vector<int>* singleElements;
    vector<int> tree;
    SegTree() : singleElements(nullptr) {}
    SegTree(vector<int>* arr) : singleElements(arr) {
        tree.resize(arr.size() - 1);
        build(...);
    }
    ...
}
int main() {
    vector<int> a(10, 1), b(10, -1);
    SegTree st1(a);
    SegTree st2();
    st2.assign(b);
    return 0;
}

I am not sure with this part of c++. Sorry for my bad English.

  • 1
    I suspect you want `std::move` and move constructors. But your question is very unclear. Can you update your question such that the code you have will actually compile? – selbie Jun 23 '19 at 21:34
  • 1
    It looks like you should get [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), particularly chapters about *pointers* and *references*. To answer your question, do you *need* to store `singleElements` in your class? Will it be used outside of your constructor? If not, you'd be best passing that vector by *const reference*. If you do need to store that initial data, but you don't need to keep it in caller (`main`), then *move semantics* are your friend. – Yksisarvinen Jun 23 '19 at 21:38
  • If you need to keep the vector in both `main` and class instance, you may want to look up `std::shared_ptr` instead of raw pointers. – Yksisarvinen Jun 23 '19 at 21:40
  • Yes, this solves my problem. – Василий Пупкин Jun 23 '19 at 21:43

1 Answers1

1

You should use moving constructor rather than copying one.

SegTree(std::vector<int> && arr);

And call it in this way:

SegTree st1(std::move(a));

Notice! After this the 'a' vector is in unspecified state, so you cannot operate on it. Take a look at the documetation!

cpp documentation