std::copy 从向量的位置到向量的位置
std::copy from vector's position to vector's position
这可能是我太累了,但我不知道如何将向量的一部分复制到新向量中。
我想做的是在起始标记所在的 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);
这可能是我太累了,但我不知道如何将向量的一部分复制到新向量中。
我想做的是在起始标记所在的 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);