对其中一个变量的多变量结构进行排序
Sorting multi-variable struct on one of it's variables
大家早上好,我正在尝试根据其中一个变量的值对结构中连接的 3 个变量进行排序。为了清楚起见,我有一个名为 edge 的结构化变量类型,它有 3 个整数:edge.a edge.b 和 edge.w。我想按 edge.w 上的值对边缘进行排序。我发现要实现这一目标,我需要使用 bool 运算符,但我还没有发现如何。这是我的代码:
struct type{
int a,b,w;
bool operator<(const edge&A) const{
return w<A.w;
};
};
type edge[6];
sort (edge);
sort() 包含在库中,并对括号中的数组执行快速排序。请帮忙,泰
尝试以下操作
#include <algorithm>
//...
struct type{
int a,b,w;
bool operator<(const type& A) const{
return w<A.w;
};
};
type edge[6];
//...
std::sort( edge, edge + 6 );
或
#include <algorithm>
#include <iterator>
//...
struct type{
int a,b,w;
bool operator<(const type& A) const{
return w<A.w;
};
};
type edge[6];
//...
std::sort( std::begin( edge ), std::end( edge ) );
另一种方法是以下
#include <algorithm>
#include <iterator>
//...
struct type{
int a,b,w;
struct sort_by_a
{
bool operator ()(const type &lhs, const type &rhs ) const
{
return lhs.a < rhs.a;
}
};
struct sort_by_b
{
bool operator ()(const type &lhs, const type &rhs ) const
{
return lhs.b < rhs.b;
}
};
struct sort_by_w
{
bool operator ()(const type &lhs, const type &rhs ) const
{
return lhs.w < rhs.w;
}
};
};
type edge[6];
//...
std::sort( std::begin( edge ), std::end( edge ), type::sort_by_a() );
//...
std::sort( std::begin( edge ), std::end( edge ), type::sort_by_b() );
//...
std::sort( std::begin( edge ), std::end( edge ), type::sort_by_w() );
相关文章:
- 从结构寻址时,MMAP变量的行为很奇怪
- 访问在 C++ 结构中声明的枚举变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 在类构造函数中使用结构变量
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 在类构造函数中定义结构变量的参数
- 为什么我们再次从结构对象创建结构变量?
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 模板化结构中的零大小成员变量
- C++ 结构中的可选变量(变量结构)
- 对其中一个变量的多变量结构进行排序
- 指向非指针变量结构的指针。这些变量在哪里,堆还是堆栈?
- 是好是坏:为了避免使用全局变量/结构体的属性/大量参数而使用巨型结构体
- Cpp变量/结构用于存储128位数据
- 第一私有变量结构中允许的OpenMP调用和指令
- VS2008传递变量-结构与结构组件-优点/缺点
- 在c++类成员函数中使用c库变量/结构成员
- 如何不迷失在执行'<'对于多变量结构