我有一个名为vector1的无符号字符向量,我希望以8字节为单位迭代向量,并使用std :: transform函数对每个块执行按位运算。变换函数将XOR< d数据存储在vector2中。这就是我现在所拥有的:
for (std::vector<unsigned char>::iterator itr = vector1.begin(); itr != vector1.end(); itr += 8)
{
// vector1 data XOR'd with KEY_IV data and output to vector2
std::transform(itr, itr += 8, std::begin(KEY_IV), std::begin(vector2), std::bit_xor<unsigned char>());
if (itr == vector1.end())
break;
}
这不符合我的要求。我也认为可能存在一个问题,因为我一次通过向量迭代8个字节,并且在转换函数内也做同样的事情。我在转换中是否需要两个(itr,itr + = 8)?
感谢。
修改 检查vector1是否为8的倍数,如果不是,则用0&#39; s
填充// check vector1 for multiples of 8, if not, pad out with 0's
for (std::vector<unsigned char>::iterator itr = vector1.begin(); itr != vector1.end(); itr += 8)
{
if ((vector1.size() % 8) != 0)
{
vector1.push_back(fmod(vector1.size(), 8));
}
}
答案 0 :(得分:1)
您在调用itr
时正在改变std::transform
。您有未指定的行为,因为它再次出现在参数列表中。
assert((vector1.size() % 8) == 0, "bad times!");
for (std::vector<unsigned char>::iterator itr = vector1.begin(); itr != vector1.end(); itr += 8)
{
// vector1 data XOR'd with KEY_IV data and output to vector2
std::transform(itr, itr + 8, std::begin(KEY_IV), std::begin(vector2), std::bit_xor<unsigned char>());
}
std::begin(vector2)
也是可疑的,你只是在写vector2
的前8个元素。你的意思是推进目的地吗?
assert((vector1.size() % 8) == 0, "bad times!");
auto dest = std::begin(vector2);
for (auto itr = vector1.begin(); itr != vector1.end(); itr += 8)
{
// vector1 data XOR'd with KEY_IV data and output to vector2
dest = std::transform(itr, itr + 8, std::begin(KEY_IV), dest, std::bit_xor<unsigned char>());
}
通过循环vector1.size() / 8
次,然后执行最终更短的xor,可以使这更安全(丢弃断言)。
size_t count = vector1.size() / 8;
auto itr = vector1.begin();
auto dest = std::begin(vector2);
for (; --count; itr += 8)
{
// vector1 data XOR'd with KEY_IV data and output to vector2
dest = std::transform(itr, itr + 8, std::begin(KEY_IV), dest, std::bit_xor<unsigned char>());
}
std::transform(itr, vector1.end(), std::begin(KEY_IV), dest, std::bit_xor<unsigned char>());