C ++:首先要声明哪个结构?

时间:2013-01-28 15:06:37

标签: c++ struct

我编写了一个使用C ++ stl set的程序。正在构造集合的struct event及其对应的binary predicate .. struct comp用于定义集合中它们之间的排序。

代码部分如下所示:

struct event
{
    int s;
    int f;
    int w;
    set<event,comp>::iterator nxt;
};
struct comp
{
    bool operator()(event a, event b)
    {
        if(a.f!=b.f)
            return a.f<b.f;
        else
        {
            if(a.s!=b.s)
                return a.s<b.s;
            else
                return a.w>b.w;
        }
    }
};

set< event , comp > S;

我面临的问题是首先编写哪个结构?我试图向前宣布两种结构。在这两种情况下我都有编译器错误。

2 个答案:

答案 0 :(得分:4)

您需要在创建std::set对象之前包含这两个定义:

std::set<event,myComp> S;

前向声明对你不起作用,因为一旦你转发声明一个类型它就变成了一个不完整的类型,在这种情况下,编译器需要知道这两种类型的布局和大小。不完整类型仅在编译器不需要知道e.x的类型的大小或布局时才起作用:指向该类型的指针,因为所有指针都具有相同的大小。

答案 1 :(得分:2)

你可以这样做。注意引用的使用。

struct event;
struct comp
{
    bool operator()(const event& a, const event& b);
}
struct event
{
    int s;
    int f;
    int w;
    set<event,comp>::iterator nxt;
};
bool comp::operator()(const event& a, const event& b)
{
    if(a.f!=b.f)
        return a.f<b.f;
    else
    {
        if(a.s!=b.s)
            return a.s<b.s;
        else
            return a.w>b.w;
    }
}