【发布时间】:2009-03-11 06:34:25
【问题描述】:
我需要处理涉及中间插入的固定数组中的数据。 而不是使用 memcpy 等。我想使用矢量。我想要的时候有问题 将向量元素复制回 c 样式数组。 代码如下:
void tryvector()
{
using namespace std;
const int MAX_SIZE=16;
BYTE myarr[MAX_SIZE]={0xb0,0x45,0x47,0xba,0x11,0x12, 0x4e};
vector<BYTE> myvec (myarr, myarr+MAX_SIZE);
vector<BYTE>::iterator it;
printf("myarr pre :");
for(int i=0;i<MAX_SIZE;++i){
printf("%02x ", myarr[i]) ;
}
printf("\nmyvec pre :")
for(it=myvec.begin(); it<myvec.end();++it){
cout<<hex<<static_cast<int>(*it)<<" ";
}
it = myvec.begin()+ 3;
myvec.insert(it,0x5f);
printf("\nmyvec post:");
for(it=myvec.begin(); it<myvec.end();++it){
cout<<hex<<static_cast<int>(*it)<<" ";
}
copy(myvec.begin(), myvec.end(), myarr); //???
printf("\nmyarr post:");
for(int i=0;i<MAX_SIZE;++i){
printf("%02x ", myarr[i]) ;
}
}
我正在使用 vs 2005。
这是警告:
warning C4996: 'std::_Copy_opt' was declared deprecated
1> c:\program files\microsoft visual studio 8\vc\include\xutility(2270) : see declaration of 'std::_Copy_opt'
1> Message: 'You have used a std:: construct that is not safe. See documentation on how to use the Safe Standard C++ Library'
1> c:\documents and settings\mhd\my documents\tesvector.cpp(50) : see reference to function template instantiation '_OutIt std::copy<std::_Vector_iterator<_Ty,_Alloc>,BYTE*>(_InIt,_InIt,_OutIt)' being compiled
1> with
1> [
1> _OutIt=BYTE *,
1> _Ty=BYTE,
1> _Alloc=std::allocator<BYTE>,
1> _InIt=std::_Vector_iterator<BYTE,std::allocator<BYTE>>
1> ]
当我运行它时,我得到了以下运行时错误:
Run-Time Check Failure #2 - Stack around the variable 'myarr' was corrupted.
请注意,我使用向量而不是列表或双端队列,因为
像上面的代码这样的“中间插入”是一个特殊的问题。
它会比“最后插入”发生得少,并且
'元素的随机访问'。
有什么解决办法吗?
任何类似的答案:“你使用 c++,放弃 c 风格的数组实现。 对所有数组实现只使用向量”并不是很有帮助。
谢谢。
【问题讨论】:
-
仅仅因为你使用 vector 而不是数组并不意味着 memcpy() 没有发生。 vector 方法比较容易理解,但是做的一样,对于大数组性能会很差。