将可用端口放入向量中以在 For 循环中使用
Getting available ports into a vector for use in a For loop
编辑:感谢 Scheff 和其他发表评论的人
我目前正在尝试与串行设备通信,并且必须将 foreach 循环更改为基于范围的 for 循环。为此,我编写了以下代码:
std::vector<QSerialPortInfo> serialList;
for (QSerialPortInfo const &serialPortInfo : serialList)
{
qDebug() << "check/n";
if (serialPortInfo.hasVendorIdentifier () && serialPortInfo.hasProductIdentifier ())
{
if (serialPortInfo.vendorIdentifier () == trackerVendorID &&
serialPortInfo.productIdentifier () == trackerProductID)
{
trackerPortName = serialPortInfo.portName ();
trackerIsAvailable = true;
}
}
}
问题是这只会生成一个空向量,因此永远不会使用 for 循环,也永远不会调用 qDebug "check"。我知道我需要在 QSerialPortInfo::availablePorts() 中添加一些东西,但我一辈子都弄不明白怎么办。
你写:
std::vector<QSerialPortInfo> serialList;
但是 QSerialPortInfo::availablePorts()
不是 return 一个 std::vector
,它 return 是一个 QList<QSerialPortInfo>
,你可以在 for 循环中按原样使用它:
QList<QSerialPortInfo> serialList = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo& serialPortInfo : serialList)
{
...
编辑:感谢 Scheff 和其他发表评论的人
我目前正在尝试与串行设备通信,并且必须将 foreach 循环更改为基于范围的 for 循环。为此,我编写了以下代码:
std::vector<QSerialPortInfo> serialList;
for (QSerialPortInfo const &serialPortInfo : serialList)
{
qDebug() << "check/n";
if (serialPortInfo.hasVendorIdentifier () && serialPortInfo.hasProductIdentifier ())
{
if (serialPortInfo.vendorIdentifier () == trackerVendorID &&
serialPortInfo.productIdentifier () == trackerProductID)
{
trackerPortName = serialPortInfo.portName ();
trackerIsAvailable = true;
}
}
}
问题是这只会生成一个空向量,因此永远不会使用 for 循环,也永远不会调用 qDebug "check"。我知道我需要在 QSerialPortInfo::availablePorts() 中添加一些东西,但我一辈子都弄不明白怎么办。
你写:
std::vector<QSerialPortInfo> serialList;
但是 QSerialPortInfo::availablePorts()
不是 return 一个 std::vector
,它 return 是一个 QList<QSerialPortInfo>
,你可以在 for 循环中按原样使用它:
QList<QSerialPortInfo> serialList = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo& serialPortInfo : serialList)
{
...