如何安全地将std :: vector的内容复制到c风格的静态数组?

mhd*_*mhd 14 c++ arrays vector

我需要操纵涉及插入中间的固定数组中的数据.而不是使用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]) ;   

    }

}
Run Code Online (Sandbox Code Playgroud)

我正在使用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 Code Online (Sandbox Code Playgroud)

当我运行它时,我得到以下运行时错误:


    Run-Time Check Failure #2 - Stack around the variable 'myarr' was corrupted.
Run Code Online (Sandbox Code Playgroud)

请注意,我使用向量而不是列表或双端队列,因为像上面的代码一样的"中间插入"是一个特殊的问题.它将发生在"插入到最后"和"元素的随机访问"之外.
有解决方案吗

任何类似的答案:"你使用c ++,删除c风格的数组实现.仅使用向量进行所有数组实现"并不是真的有用.

谢谢.

Mic*_*urr 18

问题是你正在向向量中添加内容,因此最终会有比myarr使用它初始化的数组更多的元素.

如果要将向量复制回数组,则需要将其调整大小:

myvec.resize( MAX_SIZE);
Run Code Online (Sandbox Code Playgroud)

或者您可以限制复制的元素数量:

copy( myvec.begin(), myvec.begin()+MAX_SIZE, myarr);
Run Code Online (Sandbox Code Playgroud)

如果你想让myarr数组包含所有元素,那么它需要大于MAX_SIZE,并且你已经发现人们为什么建议使用vector而不是原始数组(vector知道如何增长,数组不会).

请注意,虽然您不希望'任何类似的答案:'您使用c ++,删除c样式数组实现.仅使用向量用于所有数组实现"',您通常可以使用a vector并传递&myvec[0]给期望的例程原始数组. vector出于这个原因,需要像原始数组一样连续存储其元素.

由于您收到"不安全操作"警告,因此您使用的是Microsoft编译器.为了安全地解决问题,你应该使用checked_copy算法代替copy.正如Evgeny Lazin所指出的,您可以为数组创建一个已检查的迭代器以传递给checked_copy算法.

使副本安全而不需要Microsoft扩展的其他选项是将数组包装在一个类(可能是模板化的)中,以跟踪数组大小并提供以安全的方式将数据复制到数组中的方法.像STLSoft的array_proxy模板Boost的东西boost::array可能会有所帮助.