0

Let's say I have a struct defined as follows:

struct Record
{
  string a;
  string b;
  string c;
};

I also have a vector<Record> containing some data. I am writing a function which will take a Record and a vector<Record> as input, and I have to return all entries in the vector which match with the Record.

However, in the Record that will be passed as a parameter to the function, some of the entries will be initialised to "". This means that those entries should not be considered while comparing with entries in the vector.

I have currently written the function as follows:

vector<Record> SearchQuery (vector<Record> data, Record tosearch)
{
    if (tosearch.a != "")
    {
        for (int i = 0; i < data.size(); i++)
        {
            if (data[i].entryno != tosearch.a)
            {
                data.erase(data.begin() + i);
                i--;
            }
        }
    }
    . 
    . // I can duplicate the above part for entry b and c as well
}

However, this doesn't seem like a good manner to write the code, as there will be a lot of redundancy. Also if Record has a lot of member variables, then the code will be huge. My question is that is there a better way to fulfill the requirement I have mentioned above?

I have looked at accessing member variables through macros, but it seems that won't work out. Accessing member variables through an index for the ith variable in a struct also seems problematic. Thanks.

therainmaker
  • 4,253
  • 1
  • 22
  • 41
  • 1
    Possible duplicate of [Iterate through Struct and Class Members](http://stackoverflow.com/questions/19059157/iterate-through-struct-and-class-members) – MikeCAT Mar 13 '16 at 08:06
  • 1
    Do you not have access to the Record code? If you do, you should implement your compare function in it. – o_weisman Mar 13 '16 at 08:17
  • @o_weisman Yup, I think that should do it. I now feel stupid for not having thought of it earlier. – therainmaker Mar 13 '16 at 08:20
  • 1
    @o_weisman You don't even have to modify the `Record` code. You can implement a non member comparison function and use it with e.g. `std::copy_if`. – juanchopanza Mar 13 '16 at 08:40
  • @juanchopanza Yes, that is true :) . Personally I like the tighter coupling between object and comparison but your suggestion has greater flexibility. – o_weisman Mar 13 '16 at 09:47

0 Answers0