struct SIndexDataNew
{
1 optional short shtMarket;
2 optional string sCode;
3 optional int iDate;
4 optional map<string, double> mField;
5 optional int iTime = 0; //指标时间格式:HHMMSS,仅对分钟级别指标有效
6 optional string sName;
};
struct SIndexNew
{
1 optional vector<SIndexDataNew> vData;
};
//需求:SIndexDataNew.vData 按用户传入的排序字段(mField 中的key), 进行排序。
//解决方法:使用 c++ Lambda 表达式
bool SIndexNewSortField(const string &sSortField, const int iSortType, const int iNum, SIndexNew &sIndexNew)
{
try
{
TLOG_DEBUG("begin SIndexNewSortField, sSortField:" << sSortField << "|" << "iSortType:" << iSortType << endl);
if (!sSortField.empty())
{
switch (iSortType)
{
case 0: //倒序
{
sort(sIndexNew.vData.begin(), sIndexNew.vData.end(), [&](SIndexDataNew lhs, SIndexDataNew rhs){return lhs.mField[sSortField] > rhs.mField[sSortField];}); // Lambda 表达式 按传入的 sSortField 排序
break;
}
case 1: //顺序
{
sort(sIndexNew.vData.begin(), sIndexNew.vData.end(), [&](SIndexDataNew lhs, SIndexDataNew rhs){return lhs.mField[sSortField] < rhs.mField[sSortField];}); // Lambda 表达式 按传入的 sSortField 排序
break;
}
}
SIndexNew sIndexNewTmp;
int iEndPos = iNum >= 0 ? min(iNum, (int)sIndexNew.vData.size()) : sIndexNew.vData.size();
for (int i = 0; i < iEndPos; i++)
{
sIndexNewTmp.vData.push_back(sIndexNew.vData[i]);
}
sIndexNew.vData.swap(sIndexNewTmp.vData);
}
}
catch (std::exception &ex)
{
TLOG_ERROR("exception:" << ex.what() << endl);
return false;
}
catch (...)
{
TLOG_ERROR("Unknown exception."<< endl);
return false;
}
return true;
}
参见:https://www.cnblogs.com/DswCnblog/p/5629165.html