user8611116
user8611116

Reputation: 13

Set a predeclared but uninitialized vector as an alias of another

In the following code, I want the vector v to be set to vector in without it's contents being copied but I cannot use reference like vector<int> &v = in because v has already been declared. What changes should I make to prevent copying?

class pt
{
private:
    vector<int> v;
    int size;

public:
    void construct(int n)
    {
        for (int i = n - 1; i >= 0; --i)
        {
            v[i] = v[i - 1] + v[i - 2];
        }
    }

    pt(vector<int>& in, bool no_Copy = false)
    {
        if (no_Copy)
        {
            &v = in;    //I want to fix this
        }
        else {}

        construct(in.size());
    }
    //other functions which use `v`
};

Upvotes: 0

Views: 47

Answers (1)

alain
alain

Reputation: 12047

Something like

vector<int> v;

can not be "switched" from not being to being an alias.

You could make it always an alias, which in one case refers to the passed in vector, and in the other case to a copy of the in vector.

For example:

class pt
{
private:
    vector<int>& v;
    vector<int> v_copy;

...

pt(vector<int>& in, bool no_Copy = false)
: v(no_Copy ? in : v_copy)
{
    if(!no_Copy) v_copy = in;
}

Or you could also move from in, as @Carl suggested in a comment. This is fast but would destroy the in vector.

Upvotes: 1

Related Questions