我有一些布尔变量,想要在同一个"顺序"中更改值表。作为变量。
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]
任何想法如何快速完成这项工作? 我想我可以操纵一些二进制矢量,但这似乎很慢?
答案 0 :(得分:1)
存储变量列表,然后根据自定义比较运算符对它们进行排序。例如:
// 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