【问题标题】:how to define less operator for sruct containing vector of int如何为包含 int 向量的结构定义 less 运算符
【发布时间】:2016-03-25 08:49:25
【问题描述】:

对于以下程序,我无法同步获得递增顺序和递减顺序。正如你所看到的,输出增加和减少的顺序是不一样的。

程序:

#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

【问题讨论】:

  • 在比较中像 for(int i = 0; i

标签: c++ sorting vector operators


【解决方案1】:

随便写

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

【讨论】:

    【解决方案2】:

    您可以直接使用std::vector::operator&lt;(它会按字典顺序进行比较),例如:

    std::vector<int> a = {0,1,2};
    std::vector<int> b = {1,2,3};
    std::cout << (a < b);
    

    输出 1。

    Here 你可以找到向量实现也有其他操作符:=,!=,,>=

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 2021-02-20
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      相关资源
      最近更新 更多