-1
struct segment{
    int _gcd;
    int _count;
    segment(){
        _gcd=0;
        _count=0;
    }
    segment(int val)
    {
        _gcd=val;
        _count=1;
    }
    void mergee(segment left,segment right)
    {
        _count=0;
       _gcd=gcd(left._gcd,right._gcd);
       if(_gcd==left._gcd)
       {
           _count+=left._count;
       }
       if(_gcd==right._gcd)
       {
           _count+=right._count;
       }
    }
}seg[4*N];

I sought a solution to Ant Colony problem in CodeForces and stumbled on https://w84iit.wordpress.com/2017/06/20/ant-colony-solutioncodeforces/. The thing that confused me the most was this struct part. Is that a declaration of function inside a struct? I also see that there's function overloading in struct too. I am not quite familiar with a function inside struct, as Google search also shows that it's more common to pass structs to an outer function. How do struct functions work? Can they only modify the variables declared inside the struct? Can I return something? The example above only used the function inside struct to modify its variable values.

Richard
  • 7,037
  • 2
  • 23
  • 76

2 Answers2

9

In C++, the struct of C is generalised to a class.

In fact the only difference between a struct and a class is the default access of data members, and inheritance.

So yes, a struct can contain functions, just like a class can.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

This function inside a class is called a non-static member function.

It has an implied object parameter that is accessible through this.

When called, the object parameter is on the left of the . in class member access:

struct x {
    int data_member;
    int f(int i){
        return data_member+i;
    }
};

x y;
y.f(10);

equivalent to:

struct x {
    int data_member;
};

int f(x* _this, int i) {
   return _this->data_member + i;
}

x y;
f(&y,10);
Oliv
  • 17,610
  • 1
  • 29
  • 72