need help to search element from vector of struct

186 Views Asked by At

I have vector of struct partationPartItemTag_t type

typedef struct partationPartItemTag
{
    std::string partition;
    std::string partGroupId;
    std::string mathTuid;
    std::string partNumber;
    tag_t itemTag;
}partationPartItemTag_t;

I want to find element from vector having value for partition == 'a' and partGroupId == 'b'

I have written following code and its working fine with C++11 But now i want to modify this code as I do not have c++11 support

partationPartItemTag_t mi={'a', 'b'};
vector<partationPartItemTag_t> searchlist;
searchlist.push_back(mi);
vector<partationPartItemTag_t>::iterator flag = std::search(partationPartItemTagVec.begin(),partationPartItemTagVec.end(),searchlist.begin(),searchlist.end(),[](partationPartItemTag_t &x, partationPartItemTag_t &y){
    return ((x.partition.compare(y.partition) == 0) && (x.partGroupId.compare(y.partGroupId) == 0));  
});

Please help me to modify this code i saw few posts for function pointer but I am not able to convert this using function pointer Note: i want to chek value of 2 member in struct and I can not use lambda function or c++11

Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

A lambda is just a convenience functor that was introduced so that you can write these algorithms simpler.

But it's just a convenience. If you can't use them in this case, it's not the end of the world. After all, we couldn't for many many years. The solution is to just go back to using a functor:

struct SearchFor
{
    /* ctor omitted for brevity */
    std::string partition, partGroupId;

    bool operator()(const partationPartItemTag_t& elem) const 
    {
        return elem.partition == partition && 
               elem.partGroupId == partGroupId;
    }
};

And then use it in-line:

vector<partationPartItemTag_t>::iterator flag = 
    std::find_if(partationPartItemTagVec.begin(),
                 partationPartItemTagVec.end(),
                 SearchFor("a", "b"));
0
On

If you need to convert from C++11 to C++098 better option is to replace a lambda with a functor.

Define a functor compare as follows and call it in your algorithm in place of lambda.

struct  compare 
{
        bool operator(partationPartItemTag_t x, partationPartItemTag_t y) const
        {
            return ((x.partition.compare(y.partition) == 0) && 
             (x.partGroupId.compare(y.partGroupId) == 0) );        
        }
}
std::search(partationPartItemTagVec.begin(),
            partationPartItemTagVec.end(),
            searchlist.begin(),searchlist.end(),
compare(partationPartItemTag_t &x, partationPartItemTag_t &y) );