二元变量的置换及其值表
Permutation of binary variables and their value table
我有一些布尔变量,并希望以相同的"顺序"更改值表
for example: 2^2 = 4 combinations
0,0 = A
0,1 = B
1,0 = C
1,1 = D
Now I swap x_1 with x_2 and end up with
0,0 = A
0,1 = C
1,0 = B
1,1 = D
我正在寻找一个函数,返回值表"排序"。给定值的排列顺序。
一种方法是循环遍历所有比特的组合并将它们转换为排列状态。但是我如何在c++中做到这一点?
例如如果我的顺序是(3,2,1)
那么x_1,x_2_x_3 = 0,1,1
就会排列到1,1,0
所以
sorted_table[sort(0,1,1)] = sorted_table[6] = old_table[3]
有什么办法可以快速完成吗?我想我可以处理一些二进制向量,但这似乎很慢?
存储变量列表,然后根据自定义比较操作符对它们进行排序。例如:
// Ordering
int* _ordering;
// Variable
template<size_t T>
class Variable : public bitset<T> {
private:
char* _name; // A variable has a name.
public:
// Constructors
Variable()
:bitset<T>(), _name(NULL) {};
Variable(string bitstring, char* name)
:bitset<T>(bitstring), _name(name) {};
// Name accessor
char*& name(void) {return _name;};
// Comparison operator
bool operator<(const Variable<T> &rhs) const {
for (int oidx=0; oidx<T; oidx++)
if (bitset<T>::test(_ordering[oidx])) {
if (!rhs.test(_ordering[oidx]))
// Left is bigger.
return false;
} else
if (rhs.test(_ordering[oidx]))
// Right is bigger.
return true;
// They match at all values.
return false;
}
};
下面是一个快速而肮脏的主程序,它用8个值的变量来测试。
#include <iostream>
#include <bitset>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <algorithm>
...
#define BITS 8
int main(int argc, char* argv[]) {
int i;
// Create the ordering based on the command line arguments
_ordering = new int[BITS];
for (i=0; i<BITS; i++) _ordering[i] = atoi(argv[i+1]);
// Read in each variable
int size=(argc-BITS-1)/2;
vector< Variable<BITS> > variables;
for (i=0; i<size*2; i+=2) {
cout << "Creating bitset " << argv[BITS+1+i]<<":"<<argv[BITS+2+i]<<endl;
variables.push_back(Variable<BITS>(string(argv[BITS+i+1]), argv[BITS+i+2]));
}
// Display the variables
for (i=0; i<variables.size(); i++)
cout << variables[i] << ":" << variables[i].name() << endl;
// Sort them
cout << endl << "Sorting..." << endl;
sort(variables.begin(), variables.end());
// Display again
for (i=0; i<variables.size(); i++)
cout << variables[i] << ":" << variables[i].name() << endl;
}
输出如下:
$ ./bitsort 0 1 2 3 4 5 6 7 01 a 11 b 10 c 00 d
Creating bitset 01:a
Creating bitset 11:b
Creating bitset 10:c
Creating bitset 00:d
00000001:a
00000011:b
00000010:c
00000000:d
Sorting...
00000000:d
00000010:c
00000001:a
00000011:b
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 二元变量的置换及其值表