Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a std::set based on specific data

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!

like image 858
skmic Avatar asked Sep 01 '26 22:09

skmic


1 Answers

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*/});
like image 170
Erbureth Avatar answered Sep 03 '26 14:09

Erbureth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!