iterator_category':不是' std :: iterator_traits< _InIt>'的任何基类的成员。

时间:2017-04-13 12:48:31

标签: c++

C ++中的新手。我想创建一个动态对象数组并使用std :: sort()对它们进行排序。但是,出现了一些错误,我无法弄清楚原因。谢谢你的帮助。 错误如下所示:

> community\vc\tools\msvc\14.10.25017\include\xutility(988):
> error C2794: 'iterator_category': is not a member of any direct or
> indirect base class of 'std::iterator_traits<_InIt>'
>           with
>           [
>               _InIt=Problem
>           ]  \include\algorithm(2915):
> note: see reference to function template instantiation 'void
> std::_Debug_range<_RanIt>(_InIt,_InIt,std::_Dbfile_t,std::_Dbline_t)'
> being compiled
>           with
>           [
>               _RanIt=Problem,
>               _InIt=Problem
#include "stdafx.h"
#include "stdlib.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

class Problem{
public:
    string name;
    int t;
    int d;
    Problem() {}
    Problem(string name,int t,int d):name(name),t(t),d(d) {}
    ~Problem() {}
    bool operator<(const Problem &right) const {
        if (t == right.t) return d < right.d;
        else return t < right.t;
    }
};

void FindOrder(int H, int N, int t0, Problem ProblemSet[]);
bool compare(const Problem &left,const Problem &right) {
    if (left.t == right.t) return left.d < right.d;
    else return left.t < right.t;
}

int main()
{
    int H, N, t0;
    cin >> H;
    while (H >= 0) {
        cin >> N >> t0;
        //Problem ProblemSet = (Problem)malloc(N * sizeof(struct ProblemNode));
        Problem* ProblemSet = new Problem[N];
        for (int i = 0;i<N;i++)
            cin >> ProblemSet[i].name >> ProblemSet[i].t >> ProblemSet[i].d;
        FindOrder(H, N, t0, ProblemSet);
        delete[] ProblemSet;
        cin >> H;
    }
    return 0;
}

void FindOrder(int H, int N, int t0, Problem ProblemSet[]) {
    int total = t0;
    sort(ProblemSet[0], ProblemSet[N-1]);
    for (int i = 0;i < N;i++) {
        cout << ProblemSet[i].name << ProblemSet[i].t << ProblemSet[i].d << endl;
    }
}

1 个答案:

答案 0 :(得分:1)

void FindOrder(int H, int N, int t0, Problem ProblemSet[]) {
    int total = t0;
    sort(ProblemSet[0], ProblemSet[N-1]);   //Wrong
    for (int i = 0;i < N;i++) {
        cout << ProblemSet[i].name << ProblemSet[i].t << ProblemSet[i].d << endl;
    }
}

sort(ProblemSet[0], ProblemSet[N-1]);错了。索引到未知大小的数组将不会产生迭代器(根据std::sort的要求。你可能意味着

sort(ProblemSet, ProblemSet + N);

您可能还想更换手动动态阵列管理:

Problem* ProblemSet = new Problem[N];
....
delete[] ProblemSet;

std::vector

std::vector<Problem> ProblemSet(N);

这样做甚至可以简化您的功能界面。并排序:

void FindOrder(int H, int t0, std::vector<Problem>& ProblemSet) {
    int total = t0;
    sort(ProblemSet.begin(), ProblemSet.end());
    for (auto& p : ProblemSet) {
        cout << p.name << p.t << p.d << endl;
    }
}