1

我有一些布尔变量,并希望以与变量相同的“顺序”更改值表。

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]

任何想法如何真正快速地做到这一点?我想我可以操纵一些二进制向量,但这似乎很慢?

4

1 回答 1

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
于 2013-06-13T13:57:47.227 回答