C++ 如何仅根据三元组值对给定列的向量进行排序?
我有一个结构,里面有三个C++ 如何仅根据三元组值对给定列的向量进行排序?,c++,sorting,vector,lambda,function-object,C++,Sorting,Vector,Lambda,Function Object,我有一个结构,里面有三个int struct x{ int a, b, c; }; 我使用struct将三元组存储在向量中,因为三元组将表示源、目标和权重 vector<x> myVec; 向量myVec; 我用myVec.push_back({a,b,c})在其中添加值 到目前为止还不错,但我想根据它们的权重对它们进行排序,这将是c变量。我不确定如何在向量上使用std::sort。例如,可以使用lambda表达式 #include <vector>
int
struct x{
int a,
b,
c;
};
我使用struct将三元组存储在向量中,因为三元组将表示源
、目标
和权重
vector<x> myVec;
向量myVec;
我用myVec.push_back({a,b,c})在其中添加值代码>
到目前为止还不错,但我想根据它们的权重对它们进行排序,这将是c
变量。我不确定如何在向量上使用std::sort
。例如,可以使用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;
} );
程序输出为
2 2 2
1 1 1
3 3 3
1 1 1
2 2 2
3 3 3
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;
}
例如,可以使用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;
} );
程序输出为
2 2 2
1 1 1
3 3 3
1 1 1
2 2 2
3 3 3
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;
}
注意,这可能很容易成为std::tuple
。如果您有struct
,请编写一个自定义比较器,运算符注意,这可能很容易成为std::tuple
。如果您有struct
,请编写一个自定义比较器,运算符