用c ++子集一个向量

Sta*_*ley 0 c++ vector

在c ++中有一种简单的方法可以从具有特定属性的向量中提取元素吗?该向量包含我自己定义的名为"Individual"的类中的对象.

我正在寻找类似SQL中此命令的c ++之类的东西:

> NewVector = SELECT * FROM MyVector WHERE Age > 10
Run Code Online (Sandbox Code Playgroud)

或者这个在R中:

> NewVector <- subset(MyVector, Age > 10)
Run Code Online (Sandbox Code Playgroud)

所以基本上,我想扫描所有元素MyVectorNewVector在满足条件时添加它们MyVector[i].Age > 10.

以下是这些向量的定义方式:

> vector<Individual> MyVector(20000); // this one later gets filled with stuff

> vector<Individual> NewVector(0); // i want this to be a subset of MyVector
Run Code Online (Sandbox Code Playgroud)

Act*_*lis 7

我相信,这样做的惯用方法是std::copy_if.您可以在列表中为其提供迭代器,在新列表上提供插入器,并为谓词提供函数对象.

就像是

std::copy_if(MyVector.begin(), MyVector.end(), std::back_inserter(NewVector), [] (Individual i) { return i.Age > 10; });
Run Code Online (Sandbox Code Playgroud)

编辑:小心复制语义是你想要的.如果你已经Individual在向量本身中获得了s,而不是指针,那么这将导致NewVector不具有与之前相同的对象,因为它们正在被复制.通常,C++没有(好的)方法用另一个向量共享的对象填充向量; 你可能希望考虑一下vector<std::shared_ptr<Individual>>.