Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy function arguments in c++

Tags:

c++

I'm reading this book called accelerated c++.For 'copy' shown below

// error - no element at ret.end() 
copy(bottom.begin(), bottom.end(), ret.end());

It is mentioned in the book that it is not quiet right to use ret.end() as the third argument.But ret.end() returns the iterator for one past the last element of 'ret' container.What is the problem with this argument?They are suggesting to use 'back_inserter(ret)' instead.Why is that so?

like image 476
tez Avatar asked Feb 20 '23 18:02

tez


1 Answers

The problem with ret.end is that although it points to one past the end of the container, there may be nothing allocated at or beyond that location in memory. Since writing to memory locations that have not been allocated to your program is undefined behavior, you should indeed use back_inserter.

like image 185
Sergey Kalinichenko Avatar answered Feb 27 '23 07:02

Sergey Kalinichenko