使用实例根据特定数据筛选std::set

Filtering a std::set based on specific data

本文关键字:数据 筛选 std set 实例      更新时间:2023-10-16

我有一个类的std::集合,它存储了一些主数据。下面是我的集合的样子:

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

现在我想根据TBigClass的一些字段过滤这个集合中的数据,并将其存储在另一个集合中以供操作。

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
}
谁能告诉我一个有效的方法来完成这个?我没有安装任何库,所以详细使用boost的解决方案没有帮助。

更新:我正在开发c++ 98环境。

感谢您的阅读!

您可以使用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*/});