std::algorithm 使其更具表现力

std::algorithm to make this more expressive

我正在使用 C++17 开发自己的区块链实现。

为了尽可能多地学习,我想尽可能减少循环,转向 std::algorithm 库中的替代(和更具表现力的)循环。

在空壳中,在区块链算法中,每个块都包含它自己的哈希值和前一个块的哈希值(Genesis-Block 除外,它不包含前一个块块[容器中的第一个])。

我想在 Blockchain 对象中实现一个 Validate 函数,它接受成对的块(包含在 std::vector 中),并检查哈希值(和以前的哈希值)以确保它们没有被篡改。

当前代码(有效):

bool Blockchain::Validate() const
{
    // HASH is in ASCII
    std::array<unsigned char, 64> calculated_hash{};

    // No underflow here since Genesis-Block is created in the CTOR
    for (auto index = this->chain_.size() - 1; index > 0; --index)
    {
        const auto& current_block{this->chain_[index]};
        const auto& previous_block{this->chain_[index - 1]};

        SHA256{previous_block}.FillHash(calculated_hash);

        if (!std::equal(std::begin(calculated_hash), std::end(calculated_hash),
                        std::begin(current_block.GetPreviousHash()), std::end(current_block.GetPreviousHash())))
        {
            return false;
        }
    }

    return true;
}
    

我想知道是否有一种算法以某种方式工作 Python 对字符串执行其 ", ".join(arr) ,它在数组中的每个相邻对之间附加逗号,而是将检查直到某个条件 returns false 在这种情况下停止 运行.

TLDR:

如果这是我的容器: A B C D E F G

我想知道是否有一种算法可以断言相邻对中的条件:(A, B), (B, C), (C, D), (D, E), (E, F ), (女, 女)

并且会在条件失败时停止,例如:

A 与 B -> 正确

B 与 C -> 真

C 与 D -> False

所以算法会return假。 (听起来像是 std::all_of 的相邻实现)。

有这样的std::algorithm吗?谢谢!

如果您有一些范围 v,您希望在其中检查每个相邻元素的某些条件,并且尽早 return,您可以使用 std::adjacent_find.

先写一个比较相邻元素的lambda:

auto comp = [](auto left, auto right)
{
  return // the Negation of the actual condition
}

请注意,需要取反,以便您在到达实际 false 案例时早 return。因此,在您的情况下,A,BB,C 会比较 false,而 C,D 会比较 true。

现在您可以像这样使用 lambda:

return std::adjacent_find(std::begin(v), std::end(v), comp) == std::end(v);

在你的手动循环中,你实际上看起来是在反向迭代,在这种情况下你可以这样写:

return std::adjacent_find(std::rbegin(v), std::rend(v), comp) == std::rend(v);