c++ - 无法使用复印功能

标签 c++ c++11 vector copy

这里的 copy(这是一个通用函数)有什么问题?我无法运行代码。

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;

编译后的结果如下:

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

最佳答案

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

 #include <iterator>
 ...

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

更好的方法是构造b来自 a ,在这种情况下,编译器知道立即分配所有需要的内存并从 a 构造元素:

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

 std::vector<int> b = a;

关于c++ - 无法使用复印功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18207628/

相关文章:

c++ - 数组键是否确定 C++ 中的数组大小?

c++ - 如何使用指向结构体 vector 的迭代器 C++?

c++ - 理解 vector 乘法

matlab - 循环遍历重复向量而不显式写出重复出现的位置

c++ - 如何在我的 Ubuntu 11.04 (Natty Narwhal) 上安装 g++/gcc 4.6?

c++ - MOG2 背景扣除参数

python - 在C++中创建数据包嗅探器

c++ - std::move 模板参数是如何推导出来的?

c++ - 在 C++11 中使用 auto foo = "bar"与 std::string

C++ - 接受绑定(bind)函数作为参数并将其传递给另一个函数的模板函数