Retrieving structure from vector of structs following a find_if

Advertisements

I have written this small program to search for a struct inside a vector of structs. After this line in the code below, how should I extract the element of the vector that matched. i.e. the structure and its contents.

        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;
}

>Solution :

You can save the result of the std::find_if() as an iterator, then dereference to extract its components. Like:

#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;
}

Leave a Reply Cancel reply