gpt4 book ai didi

c++ - 用 int 和 Points 对 vector 进行排序

转载 作者:行者123 更新时间:2023-11-28 01:20:59 31 4
gpt4 key购买 nike

我在对 vector 进行排序时遇到了一些问题。我想根据第一个元素对 vector 进行排序,其中第一个元素是数字。有人可以解释一下我做错了什么以及这 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.'operator<'不匹配(操作数类型是'const Point'和'const Point')
|| (!(__y.first < __x.first) && __x.second < __y.second);
2.constexpr 函数体 'constexpr bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) [with _T1 = int; _T2 = Point]' 不是返回语句
|| (!(__y.first < __x.first) && __x.second < __y.second); } ^ ^

最佳答案

int 的比较器s 是无用的,可能是未定义的行为。编译器知道如何比较两个整数,这是语言的一部分。它还知道如何比较 std::pair 的两个实例.它不知道的是如何比较 Point 的两个实例。类,由您定义。

基本上,您有两个选择:

<强>1。提供operator<对于 Point

这将使您在以后的任何情况下都可以轻松地比较两点:

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 提供就地比较器如果您只需要比较内容以进行排序,这是一个快速的解决方案。

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 的特性。

以上选择取决于用途。如果您只需要对 vector 进行排序,或者排序逻辑不寻常,请使用 std::sort比较器。如果你想总是比较两个 Point以同样的方式,进行运算符重载。

关于c++ - 用 int 和 Points 对 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56297146/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com