gpt4 book ai didi

c++ - 如何为包含 int vector 的结构定义 less 运算符

转载 作者:行者123 更新时间:2023-11-30 01:44:26 24 4
gpt4 key购买 nike

对于以下程序,我无法同步获得升序和降序。如您所见,输出的递增顺序和递减顺序并不相同。

程序:

#include <iostream>
#include <vector>
#include <algorithm>
#include<stdio.h>

using namespace std;

struct box{
vector<int> dim;
int index;
box(vector<int> temp, int ind)
{
dim = temp;
index = ind;
}
bool operator<(const box &rhs) const
{
for(int i = 0; i < dim.size(); i++)
{
if(dim[i] >= rhs.dim[i])
{
return false;
}
}
return true;
}

void print()
{
for(int i = 0 ; i < dim.size(); i++)
{
cout<<dim[i]<<"\t";
}
cout<<endl;
}
};

int main( )
{
int n,k;

while(scanf("%d %d", &k, &n) == 2){
vector<box> arr;
vector<box> newarr;
for(int i = 0; i < k ; i++)
{
vector<int> temp;
for(int j = 0; j < n ; j++)
{
int a;
cin>>a;
temp.push_back(a);
std::sort(temp.begin(), temp.end());
}
arr.push_back(box(temp,i+1));
newarr.push_back(box(temp,i+1));
}

std::sort(arr.begin(), arr.end());
cout<<"Increasing Order"<<endl;
for(int i =0 ; i < k ; i++)
{
arr[i].print();
}
std::sort(newarr.rbegin(), newarr.rend());
cout<<"Decreasing Order"<<endl;
for(int i =0 ; i < k ; i++)
{
newarr[i].print();
}
}

return 0;
}

输入:

27 2
39 26
63 17
64 46
75 13
26 25
21 45
15 22
41 41
98 92
27 81
37 65
39 25
53 50
72 55
12 42
66 65
10 96
90 90
93 77
24 70
64 49
87 79
33 99
59 11
49 43
43 31
76 85

我的输出:

Increasing Order
12 42
24 70
25 39
11 59
15 22
25 26
21 45
41 41
31 43
43 49
37 65
46 64
50 53
17 63
26 39
33 99
49 64
90 90
77 93
10 96
65 66
55 72
13 75
27 81
76 85
79 87
92 98
Decreasing Order
76 85
33 99
92 98
79 87
77 93
90 90
10 96
65 66
55 72
27 81
37 65
50 53
46 64
49 64
43 49
41 41
31 43
26 39
24 70
17 63
13 75
11 59
25 26
21 45
12 42
25 39
15 22

最佳答案

随便写

bool operator<(const box &rhs) const
{
return dim < rhs.dim;
}

关于c++ - 如何为包含 int vector 的结构定义 less 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36216782/

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