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

std::copy from vector's position to vector's position

本文关键字:位置 向量 复制 std      更新时间:2023-10-16

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

我正在尝试做的是在 std::vector(其中 char 被类型化为字节)中找到起始标记所在的位置,并从那里复制数据,直到结束标记(在末尾,长度为 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_包含图像或音频文件的原始字节。因此向量。

答案很简单:只是复制,不要循环。循环已经在 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) );

除了复制,您还可以直接从现有向量构造一个新向量:

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