std ::从向量的位置复制到向量的位置

时间:2015-01-23 01:31:01

标签: c++ c++11 vector

这可能是我非常疲惫,但我无法弄清楚如何将一部分矢量复制到一个新的矢量中。

我正在尝试做的是在std :: vector(其中char是typedefed as byte)中找到起始标记,并从那里复制数据,直到结束标记(最后,并且是7个字符长。)

typedef char byte;
std::vector<byte> imagebytes;
std::vector<byte> bytearray_;

for ( unsigned int i = 0; i < bytearray_.size(); i++ )
{
    if ( (i + 5) < (bytearray_.size()-7) )
    {
        std::string temp ( &bytearray_[i], 5 );

        if ( temp == "<IMG>" )
        {
            // This is what isn't working
            std::copy( std::vector<byte>::iterator( bytearray_.begin() + i + 5 ),
                       std::vector<byte>::iterator( bytearray_.end() - 7 )
                       std::back_inserter( imagebytes) );
        }
    }   
}

我知道这个循环看起来很可怕,我愿意接受建议! 请注意,bytearray_包含图像的原始字节或音频文件。因此,矢量。

2 个答案:

答案 0 :(得分:5)

答案很简单:只需复制,不要循环。循环已在std::copy内。

typedef char byte;
std::vector<byte> imagebytes;
std::vector<byte> bytearray_;

// Contents of bytearray_ is assigned here.
// Assume bytearray_ is long enough.

std::copy(bytearray_.begin() + 5,
          bytearray_.end() - 7,
           std::back_inserter( imagebytes) );

答案 1 :(得分:3)

您也可以直接从现有的矢量构建新的矢量,而不是复制:

std::vector<byte> imagebytes(bytearray_.begin() + i + 5, bytearray_.end() - 7);
相关问题