C2780 when using the STL copy algorithm

1

Greetings, I'm trying to design a "copy constructor", everything was fine until I came up with the copy algorithm and I have obtained a C2780 because apparently it only recognizes 2 of 3 arguments for copy ...

#include<iostream>
#include<algorithm>

using namespace std;

// a very simplified vector of doubles
class vector {
    int sz; // the size
    double* elem; // a pointer to the elements
public:
    vector(int s) :sz{ s }, elem{ new double[s] } 
    { for (int i = 0; i<sz; ++i) elem[i] = 0.0; } // constructor
    vector(const vector&); // copy constructor: define copy
    ~vector() { delete[] elem; } // destructor
    int size() const { return sz; } // the current size
    double get(int n) const { return elem[n]; } // access: read
    void set(int n, double v) { elem[n] = v; } // access: write
};

vector::vector(const vector& arg)
// allocate elements, then initialize them by copying
    :sz{ arg.sz }, elem{ new double[arg.sz] }
{
    copy(arg, arg + sz, elem); // std::copy(); see §B.5.2
}

int main()
{
    vector v(5);
    for (int i = 0; i < v.size(); ++i) {
        v.set(i, 1.1*i);
        cout << "v[" << i << "]==" << v.get(i) << '\n';
    }
}

Thank you very much for your time.

    
asked by José Antonio Martínez Escobedo 24.06.2017 в 23:57
source

2 answers

1

What happens is that the copy function that you are trying to use receives as parameters 2 iterators / pointers to the array that you want to copy, therefore you must pass the pointer to the beginning of the array and at the end, which should be like this

Edit. Version marked as obsolete when using pointers:

copy( arg.elem, arg.elem + arg.sz, elem );

only works with vector, list, map, etc. iterators.

Alternative that will not show you the deprecated error:

memcpy( elem, arg.elem, sizeof( double ) * arg.sz );

Here is sizeof( double ) * arg.sz unlike the previous function, since bytes are being copied instead of elements.

    
answered by 28.06.2017 / 19:09
source
0

The problem is that arg is of type "vector", it is not the pointer to double that you expect.

Another additional problem is that you should not use the name "vector" for your own types together with "using namespace std;"; really, it's not good at all.

The line in question should look like:

std::copy(arg.elem, arg.elem + sz, elem); 
    
answered by 09.07.2017 в 13:24