将此scala代码转换为C++

Converting this scala code to C++

本文关键字:C++ 转换 代码 scala 将此      更新时间:2023-10-16

我有以下标量代码:

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的*操作相同。