如何用C++或者QT复写下述代码?
dt_partnum是一个DataTable。
string partNum;
int maxstep =0;
List selectedPN = new List();//选择的partnum的所有行
foreach (DataRow row in dt_partnum.Rows)
{
if (row["PartNumber"].ToString() == partNum)
{
selectedPN.Add(row);//添加到selectedPN
try
{
if (int.Parse(row["Step"].ToString()) > maxstep)//找到最大step
maxstep = int.Parse(row["Step"].ToString());
}
catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); return; }
}
}
以下是使用C++的代码示例,它是基于标准库中的vector和map实现的:
#include <iostream>
#include <vector>
#include <map>
// 假设 dt_partnum 是一个 vector<map<string, string>> 类型的变量
// map<string, string> 表示每一行数据的 key-value 对
void processDataTable(const std::vector<std::map<std::string, std::string>>& dt_partnum,
const std::string& partNum)
{
int maxstep = 0;
std::vector<std::map<std::string, std::string>> selectedPN; // 选择的partnum的所有行
for (const auto& row : dt_partnum)
{
if (row.at("PartNumber") == partNum)
{
selectedPN.push_back(row); // 添加到selectedPN
try
{
int step = std::stoi(row.at("Step"));
if (step > maxstep) // 找到最大step
maxstep = step;
}
catch (const std::exception& ex)
{
std::cout << ex.what() << std::endl;
return;
}
}
}
// 对 selectedPN 和 maxstep 进行后续处理
// ...
}
“Devil组”引证GPT后的撰写:
用 C++ STL 重写的示例代码
std::string partNum;
int maxstep = 0;
std::vector<DataRow> selectedPN; // 选择的partnum的所有行
for (const auto& row : dt_partnum)
{
if (row["PartNumber"].ToString() == partNum)
{
selectedPN.push_back(row); // 添加到selectedPN
try
{
int step = std::stoi(row["Step"].ToString());
if (step > maxstep) // 找到最大step
{
maxstep = step;
}
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return;
}
}
}
QT
QString partNum;
int maxstep = 0;
QList<DataRow> selectedPN; // 选择的partnum的所有行
for (int i = 0; i < dt_partnum.rowCount(); ++i)
{
const auto& row = dt_partnum[i];
if (row["PartNumber"].toString() == partNum)
{
selectedPN.append(row); // 添加到selectedPN
try
{
int step = row["Step"].toInt();
if (step > maxstep) // 找到最大step
{
maxstep = step;
}
}
catch (const std::exception& ex)
{
QMessageBox::critical(this, tr("Error"), QString::fromStdString(ex.what()));
return;
}
}
}