Tôi cần thao tác dữ liệu trong mảng cố định liên quan đến chèn giữa. Thay vì sử dụng memcpy, v.v. Tôi muốn sử dụng vector. Tôi gặp vấn đề khi tôi muốn để sao chép các phần tử vectơ trở lại mảng kiểu c. Dưới đây là các mã:Làm thế nào để sao chép nội dung của std :: vector thành mảng tĩnh kiểu c, an toàn?
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]) ;
}
}
Tôi đang sử dụng vs 2005. Dưới đây là những cảnh báo:
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> ]
Khi tôi chạy nó, tôi nhận được lỗi sau thời gian chạy:
Run-Time Check Failure #2 - Stack around the variable 'myarr' was corrupted.
Xin lưu ý rằng tôi sử dụng véc tơ thay vì liệt kê hoặc deque vì cách chèn 'giữa' giống như mã ở trên là juat lem. Nó sẽ xảy ra ít hơn 'chèn vào cuối' và 'truy cập ngẫu nhiên của phần tử'.
Bất kỳ giải pháp nào?
Bất kỳ câu trả lời nào giống như: "Bạn sử dụng C++, thả triển khai mảng kiểu c. Chỉ sử dụng vectơ cho tất cả triển khai mảng" không thực sự hữu ích.
Cảm ơn.
Chỉ vì bạn đang sử dụng vectơ <> thay vì mảng không có nghĩa là memcpy() không xảy ra. Các phương thức vector <> dễ hiểu hơn, nhưng cũng làm như vậy, và hiệu suất sẽ kém đối với các mảng lớn. – slacy