3

I have created two arrays List1 and List2 with new in C++. List1 is updated with data. I would like to copy List1 to List2. I tried using

std::copy(std::begin(List1), std::end(List1), std::begin(List2));

However, this does not work and gives the following error message:

error: ‘begin’ is not a member of ‘std’

Any possible suggestions for this error? Or alternative ways to copy in C++?

SKPS
  • 5,433
  • 5
  • 29
  • 63

3 Answers3

2

"I have created two arrays List1 and List2 with new in C++"

The begin and end free functions won't work on a pointer.

Even if everything is correct, you may end up with no matching call to begin(T *&)

T is the type of your pointer.

Use std::vector or std::list other STL container or just simply static arrays to work with std::begin and std::end

P0W
  • 46,614
  • 9
  • 72
  • 119
  • Is there an explanation? or they just didn't include its support – khajvah Oct 08 '13 at 16:46
  • @POW: Would you recommend using memcpy? – SKPS Oct 08 '13 at 16:51
  • @khajvah See [this](http://en.cppreference.com/w/cpp/iterator/begin), probably it answers your question – P0W Oct 08 '13 at 16:51
  • @SathishKrishnan that's why I asked what the arrays were. That will go wrong if the constructors need to do work – doctorlove Oct 08 '13 at 16:52
  • @P0W isn't that link saying std::begin *does* work on `a`, given `int a[] = { -5, 10, 15 };`? – doctorlove Oct 08 '13 at 16:54
  • @doctorlove yes I told for static array, it will work, see the answer. Also, here if a is passed in a function it won't, as arrays decays to pointer – P0W Oct 08 '13 at 16:55
  • 1
    @khajvah The explanation is simply that a pointer is a pointer, not an array. A pointer can point to the start of an array (e.g., allocated with `new[]`), but there is no portable way to tell if it does, or how big that array is. This means that implementing `end()` is essentially impossible, and it would seem pointless to provide `begin()` without `end()`. – Mikael Persson Oct 08 '13 at 16:57
0

Put this line towards the top of your cpp file:

#include <iterator>
Duncan Smith
  • 530
  • 2
  • 10
0

To use std::begin and std::end you need to include <iterator> and make sure your compiler supports C++11. However this won't fix your problem, as you cannot use them with pointers. Use std::vector instead.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91