我编写了这个小程序来搜索结构向量中的结构。在下面代码中的这一行之后,我应该如何提取匹配向量的元素。即结构及其内容。
if (std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred) != jobInfoVector.end())#include <iostream>
#include <vector>
#include <algorithm>
#include "boost/bind.hpp"
using namespace std;
struct jobInfo
{
std::string jobToken;
time_t startTime;
time_t endTime;
};
typedef struct jobInfo JobInfo;
int main()
{
std::vector<JobInfo> jobInfoVector;
JobInfo j1 = {"rec1",1234,3456};
JobInfo j2 = {"rec2",1244,3656};
JobInfo j3 = {"rec3",1254,8456};
jobInfoVector.push_back(j1);
jobInfoVector.push_back(j2);
jobInfoVector.push_back(j3);
auto pred = [](const JobInfo &jobinfo) { return jobinfo.startTime == 1234; };
if (std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred) != jobInfoVector.end())
{
cout << "got a match" << endl;
}
else
{
cout << "Did not get a match" << endl;
}
return 0;
}发布于 2022-02-18 03:28:35
您可以将std::find_if()的结果保存为迭代器,然后取消引用以提取其组件。比如:
#include <iostream>
#include <vector>
#include <algorithm>
#include "boost/bind.hpp"
using namespace std;
struct jobInfo
{
std::string jobToken;
time_t startTime;
time_t endTime;
};
typedef struct jobInfo JobInfo;
int main()
{
std::vector<JobInfo> jobInfoVector;
JobInfo j1 = {"rec1",1234,3456};
JobInfo j2 = {"rec2",1244,3656};
JobInfo j3 = {"rec3",1254,8456};
jobInfoVector.push_back(j1);
jobInfoVector.push_back(j2);
jobInfoVector.push_back(j3);
auto pred = [](const JobInfo &jobinfo) { return jobinfo.startTime == 1234; };
auto it = std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred);
if (it != jobInfoVector.end())
{
jobInfo& match = *it;
cout << "got a match" << endl;
//Do whatever job with match
}
else
{
cout << "Did not get a match" << endl;
}
return 0;
}发布于 2022-02-18 03:28:16
您只需要保留从std::find_if返回的迭代器,然后使用它。
返回值 满足条件的第一个元素的迭代器,如果没有这样的元素,则为最后一个元素。
例如,您可以应用带有初始化器的If语句 (自C++17):
if (auto it = std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred); it != jobInfoVector.end())
{
cout << "got a match" << endl;
// use it from here...
}
else
{
cout << "Did not get a match" << endl;
}https://stackoverflow.com/questions/71168032
复制相似问题