您可以使用 lambda 表达式作为示例
#include <vector>
#include <iterator>
#include <algorithm>
// ...
std::sort( std::begin( myVec ), std::end( myVec ),
[]( const auto &a, const auto &b )
{
return a.c < b.c;
} );
您可以直接在std::sort 的调用中定义 lambda 表达式对象,如上所示,也可以单独定义,如以下演示程序所示
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
struct x{
int a,
b,
c;
};
int main()
{
std::vector<x> myVec =
{
{ 2, 2, 2 }, { 1, 1, 1 }, { 3, 3, 3 }
};
for ( const auto &item : myVec )
{
std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
}
std::cout << '\n';
auto compare_by_weight = []( const auto &a, const auto &b )
{
return a.c < b.c;
};
std::sort( std::begin( myVec ), std::end( myVec ), compare_by_weight );
for ( const auto &item : myVec )
{
std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
}
std::cout << '\n';
return 0;
}
程序输出是
2 2 2
1 1 1
3 3 3
1 1 1
2 2 2
3 3 3
另一种方法是定义一个函数对象。例如。
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
struct x{
int a,
b,
c;
};
struct compare_by_weight
{
bool operator ()( const x &a, const x &b ) const
{
return a.c < b.c;
}
};
int main()
{
std::vector<x> myVec =
{
{ 2, 2, 2 }, { 1, 1, 1 }, { 3, 3, 3 }
};
for ( const auto &item : myVec )
{
std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
}
std::cout << '\n';
std::sort( std::begin( myVec ), std::end( myVec ), compare_by_weight() );
for ( const auto &item : myVec )
{
std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
}
std::cout << '\n';
return 0;
}
程序输出是
2 2 2
1 1 1
3 3 3
1 1 1
2 2 2
3 3 3