用 int 和 Points 对向量进行排序
Sorting vector of pairs with int and Points
我在排序时遇到一些问题 vectors.I 想根据第一个元素对向量进行排序,其中 Number.Can 有人解释我做错了什么以及这 2 个错误是什么意思?
我尝试使用比较功能对它进行排序,但没有它,但没有任何效果。
struct Point{
int x;
int y;
};
bool compare(int a,int b){
return a < b;
}
int main()
{
int N,Number,x,y;
cin >> N;
vector<pair<int,Point>> p;
for(int i = 0 ; i < N ; i++){
cin >> Number >> x >> y;
pair<int,Point> pom = {Number,{x,y}};
p.push_back(pom);
}
// sort(p.begin(),p.end());
// sort(p.begin().p.end(),compare);
return 0;
}
我有两个错误,但我不知道是什么意思:
1.no 匹配 'operator<'(操作数类型为 'const Point' 和 'const Point')
|| (!(__y.first < __x.first) && __x.second < __y.second); }
2.body 的 constexpr 函数 'constexpr bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) [with _T1 = int; _T2 = Point]' 不是 return 语句
|| (!(__y.first < __x.first) && __x.second < __y.second); }
^
^
int
s 的比较器没有用,可能是未定义的行为。编译器知道如何比较两个整数,这是语言的一部分。它还知道如何比较 std::pair
的两个实例。它不知道的是如何比较由您定义的 Point
class 的两个实例。
基本上,您有两个选择:
1.为 Point
提供 operator<
这将使您以后在任何情况下都可以轻松比较两点:
bool operator<(const Point& p1, const Point& p2) {
if (p1.x == p2.x)
{
return p1.y < p2.y;
}
return p1.x < p2.x;
}
2。为 std::sort
提供一个 in-place 比较器
如果您只需要比较内容以进行排序,这是一个快速的解决方案。
std::sort(p.begin(), p.end(), [](const auto& p1, const auto& p2) {
//whatever logic it takes to compare two std::pair<int, Point>
});
注意: 通用 lambda(以 const auto&
作为参数)是 C++14 的一个特性。 Lambda 本身就是 C++11 的特性。
以上选择取决于用途。如果您只需要对向量进行排序,或者排序逻辑不寻常,请使用 std::sort
比较器。如果您想始终以相同的方式比较两个 Point
,请进行运算符重载。
我在排序时遇到一些问题 vectors.I 想根据第一个元素对向量进行排序,其中 Number.Can 有人解释我做错了什么以及这 2 个错误是什么意思?
我尝试使用比较功能对它进行排序,但没有它,但没有任何效果。
struct Point{
int x;
int y;
};
bool compare(int a,int b){
return a < b;
}
int main()
{
int N,Number,x,y;
cin >> N;
vector<pair<int,Point>> p;
for(int i = 0 ; i < N ; i++){
cin >> Number >> x >> y;
pair<int,Point> pom = {Number,{x,y}};
p.push_back(pom);
}
// sort(p.begin(),p.end());
// sort(p.begin().p.end(),compare);
return 0;
}
我有两个错误,但我不知道是什么意思:
1.no 匹配 'operator<'(操作数类型为 'const Point' 和 'const Point')
|| (!(__y.first < __x.first) && __x.second < __y.second); }
2.body 的 constexpr 函数 'constexpr bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) [with _T1 = int; _T2 = Point]' 不是 return 语句
|| (!(__y.first < __x.first) && __x.second < __y.second); }
^
^
int
s 的比较器没有用,可能是未定义的行为。编译器知道如何比较两个整数,这是语言的一部分。它还知道如何比较 std::pair
的两个实例。它不知道的是如何比较由您定义的 Point
class 的两个实例。
基本上,您有两个选择:
1.为 Point
operator<
这将使您以后在任何情况下都可以轻松比较两点:
bool operator<(const Point& p1, const Point& p2) {
if (p1.x == p2.x)
{
return p1.y < p2.y;
}
return p1.x < p2.x;
}
2。为 std::sort
提供一个 in-place 比较器
如果您只需要比较内容以进行排序,这是一个快速的解决方案。
std::sort(p.begin(), p.end(), [](const auto& p1, const auto& p2) {
//whatever logic it takes to compare two std::pair<int, Point>
});
注意: 通用 lambda(以 const auto&
作为参数)是 C++14 的一个特性。 Lambda 本身就是 C++11 的特性。
以上选择取决于用途。如果您只需要对向量进行排序,或者排序逻辑不寻常,请使用 std::sort
比较器。如果您想始终以相同的方式比较两个 Point
,请进行运算符重载。