简体   繁体   English

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

[英]C++: which struct is to be declared first?

I have written a program in which i use C++ stl set . 我编写了一个使用C ++ stl set There is a struct event from which the set is being constructed, and its corresponding binary predicate .. struct comp to define the ordering between them in the set. 有一个struct event ,可从中构造该集合,其对应的binary predicate .. struct comp可定义集合中它们之间的顺序。

The code portion looks as follows: 代码部分如下所示:

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;

The problem I am facing here is which struct to write first? 我在这里面临的问题是首先要编写哪个结构? I have tried forward-declaring both the structs. 我尝试过向前声明这两个结构。 I have compiler errors in both the cases. 在这两种情况下,我都有编译器错误。

You need to include both the definitions before you create the std::set object: 在创建std::set对象之前,需要包括两个定义:

std::set<event,myComp> S;

Forward declarations won't work for you because once you forward declare a type it becomes an incomplete type and in this case the compiler needs to know the layout and size of both the types. 转发声明对您不起作用,因为一旦您声明类型,该类型便成为不完整的类型,在这种情况下,编译器需要知道这两种类型的布局和大小。 Incomplete types work only when the compiler does not need to know the size or the layout of the type for ex: pointer to the type, since all pointers have same size. 仅当编译器不需要知道ex:指向类型的指针的大小或布局时,不完整类型才起作用,因为所有指针的大小都相同。

You can do it like this. 您可以这样做。 Note the use of references. 注意引用的使用。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM