在c++中对向量进行子集设置
Subsetting a vector in c++
c++中有没有一种简单的方法可以从具有特定属性的向量中提取元素?向量包含一个名为"Individual"的类中的对象,我自己定义了这个类。
我正在寻找类似于SQL中这个命令的c++等价物:
> NewVector = SELECT * FROM MyVector WHERE Age > 10
或者R中的这个:
> NewVector <- subset(MyVector, Age > 10)
所以基本上,我想扫描MyVector
的所有元素,并在它们满足条件MyVector[i].Age > 10
时将它们添加到NewVector
。
以下是这些矢量的定义:
> vector<Individual> MyVector(20000); // this one later gets filled with stuff
> vector<Individual> NewVector(0); // i want this to be a subset of MyVector
我认为,实现这一点的惯用方法是使用std::copy_if
。您给它列表上的迭代器,新列表上的插入器,以及谓词的函数对象。
类似的东西
std::copy_if(MyVector.begin(), MyVector.end(), std::back_inserter(NewVector), [] (Individual i) { return i.Age > 10; });
编辑:注意复制语义是您想要的。如果你在向量本身中有Individual
,而不是指针,那么这将导致NewVector
没有以前的对象,因为它们正在被复制。一般来说,C++没有(好的(方法来用与另一个向量共享的对象填充向量;您可能希望考虑CCD_ 7。
您可以通过以下方式
#include <vector>
#include <iterator>
#include <algorithm>
//...
vector<Individual> MyVector(20000); // this one later gets filled with stuff
vector<Individual> NewVector; // i want
//...
auto older_than_10 = []( const Individual &i ) { return i.Age > 10; };
auto n = std::count_if( MyVector.begin(), MyVector.end(), older_than_10 );
NewVector.reserve( n );
std::copy_if( MyVector.begin(), MyVector.end(),
std::back_inserter( NewVector ), older_than_10 );
template<class F>
struct filter_t{
F f;
template<class T,class A>
std::vector<T> operator()(std::vector<T,A> const& v)const{
std::vector<T> r;
std::copy_if( v.begin(), v.end(), std::back_inserter(r), f );
return r;
}
};
template<class F,class R=filter_t<std::decay_t<F>>>
R filter(F&&f){return {std::forward<F>(f)};}
从lambda生成过滤器。用途:
auto newVec = filter([](int x){return x>10;})( oldVec );
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 如何在24位SDL_Surface上设置像素的颜色
- std::设置自定义比较器
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 如何设置一个范围来提取我想要获得的信息
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 设置到子集点云匹配
- 在c++中对向量进行子集设置