C++ 排序类,内部包含类向量
c++ sort class with class vector inside
我有一个类cl1:
class c1
{
long double * coords;
...
}
我还有一个二等 cl2:
class cl2
{
vector<cl1*> cl1_vec;
unsigned int d;
...
}
我想根据坐标[d]从cl2中对cl1_vec进行排序,使用向量的排序函数。所以我可以有类似的东西
sort(cl2_inst->cl1_vec.begin(),cl2_inst->cl1_vec.end(), ??? );
我尝试了这样的应用
对包含类的"std::vector"进行排序
C++ std::class 中的谓词函数排序
但我无法解决这个问题。
感谢您以这种方式提供的任何帮助。
我尝试过的代码:
class cl1 {
public:
long double* coords;
cl1(long double *, unsigned int);
cl1();
cl1(const cl1& orig);
virtual ~cl1();
};
class cl2 {
public:
unsigned int d;
vector<cl1*> cl1_vec;
//the srting functions
static bool compareMyDataPredicate(cl1* lhs, cl1* rhs)
{
return (lhs->coords[d] < rhs->coords[d]);
};
// declare the functor nested within MyData.
struct compareMyDataFunctor : public binary_function<my_point*, my_point*, bool>
{
bool operator()( cl1* lhs, cl1* rhs)
{
return (lhs->coords[d] < rhs->coords[d]);
}
};
...
...
}
然后在主
std::sort(cl2_inst->cl1_vec.begin(),cl2_inst->cl1_vec.end(),cl2::compareMyDataPredicate() );
此错误是因为您正在从比较器函数的静态上下文访问非静态成员d
。按以下方式使用第二种方法:
- 为该结构提供一个构造函数,该构造函数
unsigned int
参数并将成员设置为该值。 - 创建一个
compareMyDataFunctor
类型的对象,并将d
的值传递给构造函数。 - 使用此对象进行排序(std::sort 的第三个参数)
我不确定这些问题,因为您对"不起作用"在您的情况下的确切含义不够精确(不编译、编译但不排序等)。如果它没有编译(很可能是猜测),您没有发布错误消息,这也使得查找和解释问题非常困难。
以下是基于您发布的代码的一些猜测:
静态函数和函子都使用成员d
来决定对哪一列进行排序。但是d
是一个实例变量,因此它不可用于任何静态变量。函子和静态成员函数都不知道要使用哪个可能的d
,因为每个实例都有一个d
。
在不诉诸 C++11 特性 (lamdas) 的情况下执行此操作的最佳方法是为函子提供一个构造函数,该函数采用您计划使用d
。像这样:
struct compareMyDataFunctor : public binary_function<cl1*, cl1*, bool>
{
compareMyDataFunctor( unsigned int d ) : d( d ) {}
bool operator()( cl1* lhs, cl1* rhs)
{
return (lhs->coords[d] < rhs->coords[d]);
}
unsigned int d;
};
这应该可以解决问题。
不过,您发布的代码还有一些问题:
- 数组应使用类型
size_t
而不是unsigned int
进行索引。std::vector
也是如此 std::binary_function
实例化中的类型与方法中的实际类型不匹配(可能是减少代码的问题)。- 不要使用
using namespace std
(我假设你从代码中的声明中这样做)。 - 诸如此类的函子应将参数作为常量引用,而不是按值。
这就是我能想到的。下次尝试提供简短、独立、完整的示例时,人们就不必求助于猜测。
相关文章:
- C++读取行到类向量
- C++ - 是否可以让子类按值包含包含类?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 如何删除包含其他向量的向量?
- 从内部类中的方法从包含类调用方法
- boost::interprocess::managed_mapped_file 如何包含弹性向量?
- 'Vector.erase()' 不适用于类向量
- 按类成员的顺序对包含类对象的C++向量进行排序
- 包含特征向量的类的奇异大小
- 如何查找多态基类向量中包含的对象的类型?
- 如何在包含类的向量中使用 std::less
- 遍历另一个类中包含的向量
- std::包含类方法的向量
- C++ 排序类,内部包含类向量
- 包含类向量的类
- C++包含指针向量的类的析构函数
- 在c++中可以有一个包含类模板的向量吗
- 我如何使一个类包含一个向量的对象
- 包含类对象的向量在主方法中引发错误
- 扩展向量迭代器以访问所包含类/结构的数据成员