根据特定数据过滤std :: set

skm*_*mic 2 c++ filtering stl set

我有一个std :: set类,它存储了一些主数据.以下是我的设置:

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

现在我想根据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
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我一个有效的方法来实现这一目标?我没有安装任何库,因此详细说明使用boost的解决方案无济于事.

更新:我正在研究C++ 98环境.

谢谢你的阅读!

Erb*_*ica 10

您可以使用 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*/});
Run Code Online (Sandbox Code Playgroud)

  • 哇,之前没有注意到 std::inserter 。另外,如果Condition只是一次性使用,请将其转换为lambda。 (2认同)
  • 很确定 `std::inserter` 有第二个参数,即要插入之前的迭代器。 (2认同)