custom vector copy constructor, PPP2 Chapter 18 Section 18.3.1

43 views
Skip to first unread message

Osman Zakir

unread,
Sep 26, 2017, 6:37:01 PM9/26/17
to PPP-public
Dr. Stroustrup didn't show an overloaded operator+ for the vector class, so how do I get this to work?

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
}

I tried to overload the operator (+) for it, but I got two error messages, both basically saying that there's no such iterator_category tag as the one I'm trying to use.  How do I define an iterator_category tag for this class, if that's what I have to do?  

As for the class itself, this is what I have right now:

// a very simplified vector of doubles (like vector<double>)
class vector
{
 
int sz;           // the size
 
double *elem;         // pointer to the first element (of type double)
public:
 vector
(int s);
 vector
(std::initializer_list<double> lst);
 
//vector(const vector&);       // copy constructor: define copy
 vector
&operator=(const vector &);    // copy assignment
 vector
operator()(double val) { return val; }
 
~vector() { delete[] elem; }
 
int size() const { return sz; }     // return current size
 
double get(int n) const { return elem[n]; }  // access: read
 
void set(int n, double v) { elem[n] = v; }  // access: write
};

Someone please help.  Thanks in advance.

Christiano

unread,
Sep 30, 2017, 5:10:37 PM9/30/17
to PPP-public
Read:
https://chcpp.info/index.php/2017/09/12/programming-principles-and-practice-using-c-2nd-edition-bugs/

 Page 633
======================================================================

In the code:

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

The copy line should be:
copy(arg.elem,arg.elem+sz,elem);
Reply all
Reply to author
Forward
0 new messages