1

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 ==========
4

4 回答 4

7

std::copy第三个参数是一个迭代器,b.begin()改为传递:

 #include <iterator>
 ...

 auto ret = std::copy(a.begin(), a.end(), b.begin());

更好的方法是从 构造ba在这种情况下,编译器知道一次分配所有需要的内存并从构造元素a

 vector<int> b(a.begin(), a.end());

或者

 std::vector<int> b = a;
于 2013-08-13T11:17:47.807 回答
4

您需要传递一个迭代器,并且您正在传递一个std::vector<int>. 在您的情况下,您应该通过b.begin()

auto ret = copy(a.begin(), a.end(), b.begin());
//                                    ^^^^^^^

当然,达到相同结果的简单方法是

vector<int> b = a;
于 2013-08-13T11:17:32.483 回答
3

auto ret = copy(a.begin(), a.end(), b.begin());

应该做的工作。

需要的所有参数std::copy都是迭代器。

于 2013-08-13T11:18:44.313 回答
2

您必须复制 tob.begin()作为第三个参数 tocopy是一个迭代器,而不是一个容器。

auto ret = copy(a.begin(), a.end(), b.begin());
于 2013-08-13T11:17:25.477 回答