C++类向量和按归档排序
C++ Vector of Class and sorting by filed
欢迎,我有课
Class test{
string a;
string b;
}
在主
vector<test> t;
以及如何按归档排序? 对 ASC 和 DESC 进行排序?我不知道这是怎么做到的
将std::sort
与自定义比较器一起使用:
bool less_by_a(const test& lhs, const test& rhs)
{
return lhs.a < rhs.a;
}
然后
#include <algorithm>
...
std::sort(t.begin(), t.end(), less_by_a);
同样,对于大于a
变体。
有标准的算法 std::sort in C++。它可以接受指定排序顺序的谓词。
因此,要按升序对向量进行排序,您可以编写
std::sort( t.begin(), t.end(), []( const test &t1, const test &t2 ) { return ( t1.a < t2.a ); } );
前提是数据成员 A 具有公共访问控制(在您的示例中,它具有私有访问控制)。
要按降序对向量进行排序,您只需反转条件即可
std::sort( t.begin(), t.end(), []( const test &t1, const test &t2 ) { return ( t2.a < t1.a ); } );
对class test
使用内部运算符<
:
class test {
//..
string a;
strint b;
//...
bool operator<(const test& t) const
{
return a < t.a;
}
//..
};
然后
std::sort(t.begin(),t.end());
你可以像这样写一个通用比较器:
template <typename T, typename S, template <typename> class L>
struct compare : public std::binary_function <const S &, const S &, bool> {
compare (T typename S::* f) : f (f) { }
bool operator () (const S & lhs, const S & rhs) const {
return L <T> ().operator () (lhs.*f, rhs.*f);
}
private:
T typename S::* f;
};
template <template <typename> class L, typename T, typename S>
compare <T, S, L> make_compare (T typename S::* f) {
return compare <T, S, L> (f);
}
然后使用它:
std::sort (t.begin (), t.end (), make_compare <std::less> (& test::a));
但是"test::a"字段必须是公开的。
相关文章:
- 计算排序向量的向量中唯一值的计数
- 查找两个排序向量中共有的元素
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何从C++的对的排序向量中获取有关给定值的相应对
- 对象接收堆栈溢出异常 c++ 的排序向量
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 指向指针排序向量的指针向量的 C++ 向量
- 未排序向量上的lower_bound/upper_bound
- 智能指针的排序向量:神秘崩溃
- 按类型排序向量并按类型或派生类型搜索
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 字符串指针的排序向量
- 具有前导数字的字符串的排序向量
- 保证重新排序向量
- 结构解释的C 排序向量
- 更新排序向量的一个条目
- 通过在排序向量上使用二叉搜索来定位未排序向量中的元素
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 使用QuickSort算法以降序排序向量