Reputation: 506
What is wrong with copy
(which is a generic function), here? I cannot run the code.
vector<int> a(10, 2);
vector<int> b(a.size());
auto ret = copy(a.begin(), a.end(), b);
for (auto i : b) cout << i << endl;
Here's the output after compiling:
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1> MainEx.cpp
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility(2176): error C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility(2157) : see declaration of 'std::_Copy_impl'
1> c:\users\amin\documents\visual studio 2012\projects\project1\project1\mainex.cpp(40) : see reference to function template instantiation '_OutIt std::copy<std::_Vector_iterator<_Myvec>,std::vector<_Ty>>(_InIt,_InIt,_OutIt)' being compiled
1> with
1> [
1> _OutIt=std::vector<int>,
1> _Myvec=std::_Vector_val<std::_Simple_types<int>>,
1> _Ty=int,
1> _InIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>
1> ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Upvotes: 1
Views: 2302
Reputation: 45470
std::copy 3rd parameter is an iterator, pass b.begin()
instead:
#include <iterator>
...
auto ret = std::copy(a.begin(), a.end(), b.begin());
The better way is to construct b
from a
, in this case, compiler knows to allocate all needed memory at once and construct elements from a
:
vector<int> b(a.begin(), a.end());
or
std::vector<int> b = a;
Upvotes: 7
Reputation: 166
auto ret = copy(a.begin(), a.end(), b.begin());
should do the job.
all arguments of std::copy
need to be iterators.
Upvotes: 3
Reputation: 227608
You need to pass an iterator, and you are passing an std::vector<int>
. In your case, you should pass b.begin()
:
auto ret = copy(a.begin(), a.end(), b.begin());
// ^^^^^^^
Of course, the simple way to achieve the same result would be
vector<int> b = a;
Upvotes: 4
Reputation: 37487
You have to copy to b.begin()
as the third argument to copy
is an iterator, not a container.
auto ret = copy(a.begin(), a.end(), b.begin());
Upvotes: 2