对自定义对象的向量进行排序如何对包含自定义(即用户定义)对象的向量进行排序。可能,标准STL算法排序应该使用在自定义对象中的一个字段(作为排序键)上操作的谓词(函数或函数对象)。我在正确的轨道上吗?
3 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
C+11
#include <vector>#include <algorithm>using namespace std;vector< MyStruct > values;sort( values.begin( ), values.end( ), [ ]
( const MyStruct& lhs, const MyStruct& rhs ){
return lhs.key < rhs.key;});C+14
#include <vector>#include <algorithm>using namespace std;vector< MyStruct > values;sort( values.begin( ), values.end( ), [ ]
( const auto& lhs, const auto& rhs ){
return lhs.key < rhs.key;});
繁花不似锦
TA贡献1851条经验 获得超4个赞
std::sortoperator<
struct X {
int x;
bool operator<( const X& val ) const {
return x < val.x;
}};struct Xgreater{
bool operator()( const X& lx, const X& rx ) const {
return lx.x < rx.x;
}};int main () {
std::vector<X> my_vec;
// use X::operator< by default
std::sort( my_vec.begin(), my_vec.end() );
// use functor
std::sort( my_vec.begin(), my_vec.end(), Xgreater() );}- 3 回答
- 0 关注
- 628 浏览
添加回答
举报
0/150
提交
取消
