将此scala代码转换为C++
Converting this scala code to C++
我有以下标量代码:
val gates = varNode.getGates()
val inMsgs = gates.map(g => g.getEndGate.getMessage())
val variableMarginal = inMsgs.reduceLeft((msg1, msg2) => msg1 * msg2)
这与C++中的以下内容相同吗(假设我们知道类型,并且使用的底层C++容器是一个向量)?
std::vector<Gate *> gates = varNode.getGates();
// Assume that the first gate always has a valid message
double marginal = gates[0]->getEndGate()->getMessage();
for (int i = 1; i < gates.size(); ++i)
marginal *= gates[i]->getEndGate()->getMessage();
我被reduceLeft函数弄糊涂了。无法理解它的作用。
[EDIT]Gate类定义如下:
sealed abstract class Gate(initialMsg: SingleFactor) {
type END_GATE <: Gate
private var endGate: Option[END_GATE] = None
private var message: SingleFactor = initialMsg
private var oldMessage: SingleFactor = initialMsg
def setEndGate(gate: END_GATE) { endGate = Some(gate) }
def getEndGate(): END_GATE = endGate.get
def setMessage(newMessage: SingleFactor, msgIndex: Long) {
oldMessage = message
message = newMessage
}
def getMsgIndex(): Long = msgIndex
def getMessage(): SingleFactor = message
def getOldMessage(): SingleFactor = oldMessage
}
据我所知,您需要SingleFactor的实现,并且知道它的*运算符是否重载,那么您就可以推断reduceLeft在做什么。
我假设inMsgs是映射操作完成后SingleFactor元素的向量(通过.getMessage())。
reduceLeft将获取第一个SingleFactor,并对第二个SingleFactor使用*运算符,其结果将对第三个SingleElement再次使用*运算符等等,从而产生一个值,该值将存储在变量Marginal中。
关于reduceLeft的一些用法示例,您可以阅读以下内容:http://alvinalexander.com/scala/scala-reduceleft-examples
为了诊断reduce的作用,您还可以将reduceLeft调用更改为如下内容:(假设您能够执行给定的Scala代码)
# the semicolons are not needed but are added in case you copy paste/single line the code
val variableMarginal = inMsgs.reduceLeft((msg1, msg2) => {
val result = msg1 * msg2;
println("msg1: "+ msg1 + " msg2: "+ msg2 + " result: "+result);
result })
我认为您可以用accumulate(API可以在这里找到:http://en.cppreference.com/w/cpp/algorithm/accumulate)在这种情况下,您提供了一个BinaryOperation,它与Scala的SingleFactor的*操作相同。
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 将无符号char*转换为std::istream*C++