是否有基于范围的类案例控制结构
Is There a Range Based case-Like Control Structure
说在 运行-time 我建立了一些 events 与发生时间。现在我在系统中有某些实体,我需要确定哪些实体受到这些事件的影响.
举个例子,我有:
- Entity1 在时间 1
初始化
- EventRed 发生在时间 3
- Entity2 在时间 8
初始化
- EventBlue 发生在时间 9
- EventYellow 发生在时间 11
- Entity3 在时间 13
初始化
这应该导致:
- 实体1是白色的
- 实体2是绿色的
- 实体3是黑色
我想要一个类似于 case
的控制结构来执行此操作,它支持失败,并且谁的案例被评估为 "greater than or equal to this value"。我想要这样的语法:
for(auto& i : Entity) {
?switch(i.GetInitializedTime()) {
?case(Red.GetOccuranceTime()):
i.AddRed();
?case(Blue.GetOccranceTime()):
i.AddBlue();
?case(Yellow.GetOccuranceTime()):
i.AddYellow();
}
}
是否有这样的控制结构,或者我是否必须兼顾所有 if 语句?
没有什么能满足您的需求。您必须为此编写自己的 class。实际上,它看起来像是 <time, function>
对的排序向量。
即使是 switch 语句的 GCC "range extension" 也采用固定范围。
当 事件 时间在设计时未知时,甚至 gcc's range based case statements are . As such the best solution is to contain the events in a map
.
因为在最初的问题中,事件只是一个导致在entity
上调用特定方法的数字,这个过程可以通过删除事件对象;让 map
使用 事件 中包含的数字,查找它会调用的 entity
方法。例如:map<int, function<void(entity&)>> events
可以填充为:
events[3] = mem_fn(&entity::AddRed);
evnets[9] = mem_fn(&entity::AddBlue);
events[11] = mem_fn(&entity::AddYellow);
填充 events
后,case
语句可以替换为遍历 events
,从 entity i
的 GetInitializedTime()
开始:
for(auto j = events.upper_bound(i.GetInitializedTime()); j != events.end(); ++j) {
j->second(i);
}
upper_bound
用于查找起始迭代器 this 因为它:
Returns an iterator pointing to the first element that is greater than key
This live example 使用了上面的功能,但是为了展示它使用了按位数组索引。索引时entity::colorArray
最低有效位是布尔值,表示是否添加了蓝色,中间位是黄色,最高有效位是红色。
说在 运行-time 我建立了一些 events 与发生时间。现在我在系统中有某些实体,我需要确定哪些实体受到这些事件的影响.
举个例子,我有:
- Entity1 在时间 1 初始化
- EventRed 发生在时间 3
- Entity2 在时间 8 初始化
- EventBlue 发生在时间 9
- EventYellow 发生在时间 11
- Entity3 在时间 13 初始化
这应该导致:
- 实体1是白色的
- 实体2是绿色的
- 实体3是黑色
我想要一个类似于 case
的控制结构来执行此操作,它支持失败,并且谁的案例被评估为 "greater than or equal to this value"。我想要这样的语法:
for(auto& i : Entity) {
?switch(i.GetInitializedTime()) {
?case(Red.GetOccuranceTime()):
i.AddRed();
?case(Blue.GetOccranceTime()):
i.AddBlue();
?case(Yellow.GetOccuranceTime()):
i.AddYellow();
}
}
是否有这样的控制结构,或者我是否必须兼顾所有 if 语句?
没有什么能满足您的需求。您必须为此编写自己的 class。实际上,它看起来像是 <time, function>
对的排序向量。
即使是 switch 语句的 GCC "range extension" 也采用固定范围。
当 事件 时间在设计时未知时,甚至 gcc's range based case statements are map
.
因为在最初的问题中,事件只是一个导致在entity
上调用特定方法的数字,这个过程可以通过删除事件对象;让 map
使用 事件 中包含的数字,查找它会调用的 entity
方法。例如:map<int, function<void(entity&)>> events
可以填充为:
events[3] = mem_fn(&entity::AddRed);
evnets[9] = mem_fn(&entity::AddBlue);
events[11] = mem_fn(&entity::AddYellow);
填充 events
后,case
语句可以替换为遍历 events
,从 entity i
的 GetInitializedTime()
开始:
for(auto j = events.upper_bound(i.GetInitializedTime()); j != events.end(); ++j) {
j->second(i);
}
upper_bound
用于查找起始迭代器 this 因为它:
Returns an iterator pointing to the first element that is greater than key
This live example 使用了上面的功能,但是为了展示它使用了按位数组索引。索引时entity::colorArray
最低有效位是布尔值,表示是否添加了蓝色,中间位是黄色,最高有效位是红色。