0

我正在尝试使数字电子问题适应基于 C++ STL 的程序。

最初我有 4 个输入 C1、C2、C3、C4。这意味着我总共有 16 种组合:

0000
0001
.
.
.
1111

我有一个由定义的多图

typedef std::pair<int, int> au_pair; //vertices
typedef std::pair<int, int> acq_pair; //ch qlty
typedef std::multimap<int, acq_pair> au_map;
typedef au_map::iterator It_au;

没有。的模拟取决于au_map. 例如:如果au_map.size() = 5我将有 C1、C2、C3、C4、C5。因此 2^5 = 32 例。

例如:如果是au_map.size()=4,我需要模拟我的算法 16 个案例。

for(It_au it = a_map.begin(); it != a_map.end(); it++)
{
  acq_pair it1 = it->second;
  //case 0:
  //C3 = 0, C2 = 0, C1 = 0, C0 = 0 
  //Update it1.second with corresponding C values

  //simulate algorithm

  //case 1:
  //C3 = 0, C2 = 0, C1 = 0, C0 = 1 
  //simulate

  .........
  //case 15: 
  //C3 = 1, C2 = 1, C1 = 1, C0 = 1 
  //simulate

}
4

2 回答 2

1

不是最好的主意。for现在,通过手动设置 C1-C4 并在循环中编写一些模拟例程,您正在做很多无用的工作。

自动化它。

使用一些抽象State-Simulator映射器Simulator实际上代表一些具体的功能对象)。

typedef char State;

struct basic_simulator {
   // You could also pass some other parameters to your
   // simulator
   virtual void operator()(...) = 0
};

struct concrete_simulator : public basic_simulator {
   virtual void operator()(...) {
      // Do something concrete
      // Trolololo
   }
};

typedef basic_simulator Simulator;

在这种情况下,您的实际包装器看起来像std::map<State, Simulator*> map;


您接下来需要做的是从您的状态中获取C1-C4值,该状态定义为char. 使用位运算符。

您的所有状态都可以定义为0-15转换为二进制 ( 2 -> 0010) 的数字。因此,要获得C1-C4值,您只需进行适当的转换:

// C1 C2 C3 C4
// -----------
// 1  1  1  1
State state = 15;

for (int i = 3; i >= 0; i--) {
   // State of some of the inputs, defined by one bit
   InputState C_xx = ((state >> i) & 1);
}

现在只需将所有这些0-15状态映射到适当的模拟函子:

std::map<State, Simulator*> mapper;
// Generally speaking, you should use some sort of
// smart pointer here
mapper[0] = new concrete_simulator(...);
mapper[1] = ...

真正酷的是你只能拥有 3 或 4 个具体的模拟器,它们将相应地映射到某些状态。

在这种情况下,调用实际模拟将意味着:

  // Fire appropriate simulation object
  (*(mapper[actual_state]))(...);

并且进行所有可能的模拟意味着迭代每个地图元素。


更新:相同的技术可用于您有超过4个输入的状态/单个输入状态可以有两个以上的可能值。

只需编写适当的映射函数和状态生成器。

于 2010-06-24T14:51:25.043 回答
0

嗯...为什么不让for循环为您枚举各种组合?

for (size_t i = 0; i != 16; ++i)
{
  bool const c1 = i & 1;
  bool const c2 = i & 2;
  bool const c3 = i & 4;
  bool const c4 = i & 8;

  // your algorithm
}

比手动设置要容易一些。

于 2010-06-24T15:34:15.140 回答