所以,已经有答案了。但只是转储代码,没有任何解释。不好。不确定,你为什么接受。总之……
我想添加一个不同方法的答案,并解释步骤。
基本上,如果您想要一个二进制数的所有组合,那么您可以简单地“计数”或“加一”。 3 位值的示例。这将是十进制 0, 1, 2, 3, 4, 5, 6, 7 和二进制 000, 001, 010, 011, 100, 101, 110, 111。你看这是简单的计数。
如果我们回想起学生时代,我们学习了布尔代数和一点自动机理论,那么我们会记得这种计数操作是如何在低级别完成的。我们总是翻转最低有效位,如果有从 1 到 0 的转换,那么我们基本上发生了溢出,也必须翻转下一位。这就是二进制加法器的原理。我们希望在我们的示例中始终添加 1。因此,将 1 加到 0,结果为 1,则不会溢出。但是加 1 到 1,结果是 0,那么我们有一个过低,必须加 1 到下一位。这将有效地翻转下一位,依此类推。
这种方法的优点是,我们并不总是需要对所有位进行操作。所以,复杂度不是 O(n),而是 O(log n)。
附加优势:非常适合您使用std::bitset 的要求。
第三个优势,也许不是那么明显:您可以将计算下一个组合的任务与程序的其余部分分离。无需将您的实际任务代码集成到这样的功能中。这也是为什么std::next_permutation是这样实现的原因。
而且,上面描述的算法适用于所有值,不需要排序或其他必要的东西。
那部分是你要求的算法。
下一部分是针对您的要求,即只有某些位可以更改。当然,我们需要指定这些位。而且因为您正在使用std::bitset 掩蔽在这里没有解决方案。更好的方法是使用索引。含义,给出允许更改的位的位位置。
然后我们可以使用上述算法,只需要一个额外的间接。所以,我们不使用bits[pos],而是使用bits[index[pos]]。
索引可以使用初始化列表轻松存储在std::vector 中。我们还可以从字符串或其他任何东西中导出索引向量。我以std::string 为例。
以上所有将产生一些简短/紧凑的代码,只有几行并且易于理解。我还添加了一些使用此功能的驱动程序代码。
请看:
#include <iostream>
#include <vector>
#include <string>
#include <bitset>
#include <algorithm>
#include <cassert>
constexpr size_t BitSetSize = 32U;
void nextCombination(std::bitset<BitSetSize>& bits, const std::vector<size_t>& indices) {
for (size_t i{}; i < indices.size(); ++i) {
// Get the current index, and check, if it is valid
if (const size_t pos = indices[i]; pos < BitSetSize) {
// Flip bit at lowest positions
bits[pos].flip();
// If there is no transition of the just flipped bit, then stop
// If there is a transition from high to low, then we need to flip the next bit
if (bits.test(pos))
break;
}
}
}
// Some driver code
int main() {
// Use any kind of mechanism to indicate which index should be changed or not
std::string mask{ "x00x0000x000000x00x00x000x000x" };
// Here, we will store the indices
std::vector<size_t> index{};
// Populated the indices vector from the string
std::for_each(mask.crbegin(), mask.crend(), [&, i = 0U](const char c) mutable {if ('x' == c) index.push_back(i); ++i; });
// The bitset, for which we want to calculate the combinations
std::bitset<BitSetSize> bits(0);
// Play around
for (size_t combination{}; combination < (1 << (index.size())); ++combination) {
// This is the do something
std::cout << bits.to_string() << '\n';
// calculate the next permutation
nextCombination(bits, index);
}
return 0;
}
此软件已使用 C++17 编译为 MSVC 19 社区版
如果您还有其他问题或需要更多说明,我很乐意为您解答