In the book Programming Principles and Practice with C++ by B. Stroustrup I have come across a piece of code where the argument is the array of a basic version of the vector class. The class is defined as
class vector {
int sz;
double * elem;
public:
vector(const vector &);
//...
};
//...
vector::vector(const vector &arg)
:sz{arg.sz},elem{new double[arg.sz]}
{
copy(arg.elem,arg.elem.sz,elem);
}
My questions: is 'arg.elem.sz' a valid expression? If yes, What is this accessing?
(By the way, I have tried to write a simple piece of code to try this, but I get an error. As arg.elem is a pointer, it expects me to do something more like 'arg.elem->')
Thanks!
EDIT/UPDATE: the syntax seems to be correct. Looking at the definition of copy, the argument is an 'iterator'. I suspect there must be something about converting the argument to an iterator type, then getting the sz-th pointed element becomes accessing the element of the iterator? Clarifications welcomed :)
This is just a typo, the arg.elem.sz
is not a valid expression because the arg.elem
is a double*
which has no member to access (nor with the ->
opertor). It should be arg.elem + arg.sz
there because this is how the std::copy
works.
In your update you asked about the iterator and the std::copy
algorithm. The std::copy
is a function template which accepts any type as input and as output iterators if they satisfy the requirements of an input iterator and of an output iterator. A pointer to an array element satisfies the mentioned requirements, so the arg.elem
as being an double*
can be used as an iterator.
If we change the questioned line of code to the following, it will make sense:
copy(arg.elem, arg.elem + arg.sz, elem);
The code above will copy the content of array between arg.elem
and arg.elem + arg.sz
to the array pointed by elem
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With