c# - 将 C# 中的 "from ... in "迭代转换为 C++ (Qt)

标签 c# c++ qt loops

我有一个用 C# 编写的片段,现在我想将它转换为 Qt 环境。 C#代码如下:

double xSum = (from p in this select p.X).Sum();
double ySum = (from p in this select p.Y).Sum();

注意:在 c# 版本中变量 p 不是预定义的。

我尝试用 foreach 和 while 循环转换它,但出现了很多错误。你能帮我做吗?

这是我的qt版本,不能用

QPointF p;
double xSum = 0;
double ySum = 0;
foreach(p, this)
{
   xSum = xSum + p.rx();
   ySum = ySum + p.ry();
}

主要问题:Qt 中“from in”的等价物是什么?

最佳答案

C++ 为此使用 lambda:

double xSum = std::accumulate(begin(), end(), 0.0,
  [](double d, QPointF p) { return d + p.rx(); } );
double ySum = std::accumulate(begin(), end(), 0.0,
  [](double d, QPointF p) { return d + p.ry(); } );

或者:

 double xSum = 0;
 std::for_each(begin, end, [&](QPointF p) { xSum += p.rx(); });

最直接的转换是

 double xSum = 0;
 for (auto p : *this) { 
   xSum += p.rx(); 
 }

关于c# - 将 C# 中的 "from ... in "迭代转换为 C++ (Qt),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368889/

相关文章:

C# 对象到字符串并返回

c# - 如何使用下一个和上一个节点引用有效地对节点列表进行排序?

c# - 等待事件 - 比轮询更好的解决方案?

c# - 尝试在接口(interface)上使用 foreach 时出现 NullReferenceException

c++ - "heterogeneous-object"类中的复制构造函数

c++ - 使用模板时,constexpr 函数不是 constexpr

c++ - QLineEdit : setValidator for 4bytes unsigned Integer not working

c++ - 静态基类型和动态派生类型的输出

c++ - Qt 找不到服务 - "org.qt-project.qt.mediaplayer"

c++ - 使用 QDomDocument 类的 xml 文件中的 Lastchild