uninitialized_copy测试代码示例

本文展示了两个C++的uninitialized_copy测试代码示例。第一个示例在未初始化拷贝时出现错误,通过在头部添加相应代码后得以解决,成功将v1的数据拷贝到data内存区域。第二个测试代码的输出结果为...
摘要由CSDN通过智能技术生成

原测试代码如下:

int main() {
	vector<int>v1{1,3,5,7,9,2,4,6,8};
	
	allocator<int>alloc;
	auto data = alloc.allocate(9);
	uninitialized_copy(v1.begin(),v1.end(), data);

	auto end = data + 9;

	while(data!=end) {
		cout << *data <<" ";
		data++;
	}
	cout << endl;

	

	system("pause");
	return 0;
}

运行后报错界面如下:

1>------ 已启动生成: 项目: ConsoleApplication1, 配置: Debug Win32 ------
1>  test2.cpp
1>e:\0000softwareinstall\visualstudio\vc\include\xmemory(350): error C4996: 'std::_Uninitialized_copy0': 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>  e:\0000softwareinstall\visualstudio\vc\include\xmemory(336): note: 参见“std::_Uninitialized_copy0”的声明
1>  e:\study\c++\primer练习程序\consoleapplication1\consoleapplication1\test2.cpp(10): note: 参见对正在编译的函数 模板 实例化“_FwdIt std::uninitialized_copy<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>,int*>(_InIt,_InIt,_FwdIt)”的引用
1>          with
1>          [
1>              _FwdIt=int *,
1>              _InIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>
1>          ]

在其头部加#define _SCL_SECURE_NO_WARNINGS,即可运行成功

#define _SCL_SECURE_NO_WARNINGS
#include<vector>
# include<iostream>
using namespace std;

int main() {
	vector<int>v1{ 1,3,5,7,9,2,4,6,8 };
	allocator<int>alloc;
	auto data = alloc.allocate(9);
	uninitialized_copy(v1.begin(), v1.end(), data);

	auto end = data + 9;

	while (data != end) {
		cout << *data << " ";
		data++;
	}
	cout << endl;



	system("pause");
	return 0;
}

输出结果为:

1 3 5 7 9 2 4 6 8

即,我们将v1中的数据拷贝到了以data为起始地址的内存中

测试代码二:

#define _SCL_SECURE_NO_WARNINGS
#include<vector>
# include<iostream>
using namespace std;

int main() {
	vector<int>v1{ 2,4 };
	vector<int>v2{ 1,3,5,7,9,2,4,6,8 };
	
	uninitialized_copy(v1.begin(), v1.end(), v2.begin());

	for (auto a:v2) {
		cout << a << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}

输出结果:

2 4 5 7 9 2 4 6 8
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值