【发布时间】:2023-03-09 08:35:01
【问题描述】:
int *arr = (int*) malloc(100*sizeof(int));
int *arr_copy = (int*) malloc(100*sizeof(int));
srand(123456789L);
for( int i = 0; i < 100; i++) {
arr[i] = rand();
arr_copy[i] = arr[i];
}
// ------ do stuff with arr ------
// reset arr...
std::copy(arr_copy, arr_copy+100, arr);
编译时我收到std::copy()的警告:
c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(2227):
warning 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'
我知道如何禁用/忽略警告,但是是否有一种简单的单行解决方案可以从未检查的指针中生成“检查的迭代器”?类似的东西(我知道 cout 不是像 int* 这样的未经检查的指针,而只是例如):
ostream_iterator<int> out(cout," ");
std::copy(arr_copy, arr_copy+numElements, out);
我不想写一个全新的专业class my_int_arr_output_iterator : iterator...。但是我可以使用现有的迭代器之一吗?
---编辑---
由于我使用 c 样式数组和 malloc 而不是 STL 容器有很多问题,所以我只想说我正在编写一个小程序来测试不同排序算法的性能和内存使用情况。您在上面看到的代码 sn-p 是针对问题的专用版本(原始代码是具有多种方法的模板类,针对不同类型数组中不同数量的元素测试一种算法)。
换句话说,我确实知道如何使用 STL 容器(向量)及其迭代器(向量::begin/end)来做到这一点。我不知道的是我问的是什么。
谢谢,但如果不是我,希望其他人会从答案中受益。
【问题讨论】:
-
你在 c++ 中使用 malloc 有什么原因吗?
-
您应该使用
std::vector<int>,除了使您的代码更安全、更易于推理之外,它恰好可以解决您的问题。就个人而言,我总是在任何新项目开始时禁用该警告。 -
@GManNickG:我不能使用矢量。见编辑。
标签: c++ algorithm stl iterator