6

I have a std::set of a class which stores some master data. Below is how my set looks like:

std::set<TBigClass, TBigClassComparer> sSet;
class TBigClassComparer
{
 public:
 bool operator()(const TBigClass s1, const TBigClass s2) const
 {
   //comparison logic goes here
 }
};

Now I want to filter data in this set based on some fields of the TBigClass and store it in another set for manipulation.

std::set<int>::iterator it;
for (it=sSet.begin(); it!=sSet.end(); ++it)
{
  //all the records with *it.some_integer_element == 1)
  //needs to be put in another set for some data manipulation
}

Could anyone tell me an effective way to accomplish this? I do not have any libraries installed so solutions detailing use of boost would not help.

Update: I am working on C++98 environment.

Thank you for reading!

1
  • 5
    First look for efficiency here: If TBigClass really is a big class, use const & in the operator(). Taking this by value is no a good idea.
    – dornhege
    Jun 24, 2014 at 12:49

1 Answer 1

14

You can use std::copy_if

struct Condition {
    bool operator()(const T & value) {
        // predicate here
    }
};
std::set<T> oldSet, newSet;

std::copy_if(oldSet.begin(), oldSet.end(), std::inserter(newSet, newSet.end()), Condition());
// or
std::copy_if(oldSet.begin(), oldSet.end(), std::inserter(newSet, newSet.end()), [](const T & value){/*predicate here*/});
6
  • 2
    Wow, didn't notice std::inserter before. Also, if Condition is only for one-time use, convert it to lambda.
    – Sheen
    Jun 24, 2014 at 12:58
  • Thanks, looks like I'm still halfway stuck in C++03 world
    – Erbureth
    Jun 24, 2014 at 13:07
  • 2
    Pretty sure std::inserter takes a second argument, the iterator to insert before. Jun 24, 2014 at 13:07
  • 1
    @JosephMansfield You're right, it does, thanks, edited.
    – Erbureth
    Jun 24, 2014 at 13:12
  • 1
    @Erbureth it works like a charm :) many thanks I am using reverse_copy_if and !Condition Thanks again
    – skmic
    Jun 24, 2014 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.