C++;案例申报? 我试图把一个数字电子问题改编成一个基于C++的STL程序。

C++;案例申报? 我试图把一个数字电子问题改编成一个基于C++的STL程序。,c++,stl,multimap,C++,Stl,Multimap,最初我有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::itera

最初我有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;
不是最好的主意。现在,通过手动设置C1-C4和在
for
循环中编写一些模拟例程,您正在做很多无用的工作

实现自动化。

使用一些抽象的
状态模拟器
映射器(其中
模拟器
实际上代表一些具体的功能对象)

在本例中,实际的包装器看起来像
std::map


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

您的所有状态都可以定义为转换为二进制(
2->0010
)的
0-15
数字。因此,要获得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] = ...
进行所有可能的模拟意味着迭代每个地图元素


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


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

哼。。。为什么不让
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
}

比手动设置要容易一些。

为什么std::map比std::vector更可取?使用std::vector肯定会获得更好的性能。@并且在16种状态下,
std::vector
中的查找时间将优于
O(log N)
中的查找时间
std::map
。但仅仅因为状态数随着
A^N
而增长,其中
A
代表可能的值,
N
代表输入数,
std::map
将提供更好的渐近性能。是的,为什么还要在评测之前谈论性能呢?@还有一点要提的是,
std::map
可以很容易地切换到,例如,
boost::unordered_map
授予
O(1)
查找时间。
std::map<State, Simulator*> mapper;
// Generally speaking, you should use some sort of
// smart pointer here
mapper[0] = new concrete_simulator(...);
mapper[1] = ...
  // Fire appropriate simulation object
  (*(mapper[actual_state]))(...);
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
}