【发布时间】:2011-05-15 04:58:53
【问题描述】:
我有这个结构的 std::vector:
struct MS
{
double aT;
double bT;
double cT;
};
我想使用 std::sort 以及 std::lower_bound/equal_range 等...
我需要能够对其进行排序并在结构的前两个元素中的任何一个上查找它。所以目前我有这个:
class MSaTLess
{
public:
bool operator() (const MS &lhs, const MS &rhs) const
{
return TLess(lhs.aT, rhs.aT);
}
bool operator() (const MS &lhs, const double d) const
{
return TLess(lhs.aT, d);
}
bool operator() (const double d, const MS &rhs) const
{
return TLess(d, rhs.aT);
}
private:
bool TLess(const double& d1, const double& d2) const
{
return d1 < d2;
}
};
class MSbTLess
{
public:
bool operator() (const MS &lhs, const MS &rhs) const
{
return TLess(lhs.bT, rhs.bT);
}
bool operator() (const MS &lhs, const double d) const
{
return TLess(lhs.bT, d);
}
bool operator() (const double d, const MS &rhs) const
{
return TLess(d, rhs.bT);
}
private:
bool TLess(const double& d1, const double& d2) const
{
return d1 < d2;
}
};
这允许我使用 MSaTLess() 调用 std::sort 和 std::lower_bound 以根据 aT 元素进行排序/查找,并使用 MSbTLess() 根据 bT 元素进行排序/查找。
我想摆脱仿函数并改用 C++0x lambda。对于相对简单的排序,因为 lambda 会将两个 MS 类型的对象作为参数。
但是对于 lower_bound 和其他二进制搜索查找算法呢?他们需要能够调用带有 (MS, double) 参数的比较器,以及相反的 (double, MS),对吗?在调用 lower_bound 时,如何最好地为这些提供 lambda?我知道我可以创建一个带有正在搜索的所需键值的 MS 虚拟对象,然后使用与 std::sort 相同的 lambda,但是有没有办法在不使用虚拟对象的情况下做到这一点?
【问题讨论】:
标签: search sorting stl lambda c++11