0
struct Task{
    int value,time,deadline;
    bool operator < (const Task& t1)const{
        return d<t1.deadline;
    }
}task[1000];

I've read this block of code of struct initialization. the first line, initialize variables, is easy to grasp. What about the second line? the bool operator thing. Seems like some kind of sorting rules. I have never seen any code like this in cpp before, could someone help me to understand it?

Alex Liu
  • 57
  • 4
  • Structs of C++ are practically classes. Think it as method. – Savrona Sep 22 '21 at 14:58
  • 3
    Note that the code has a typo; `d – Pete Becker Sep 22 '21 at 14:59
  • 1
    This is not really a question for [SO], you need tutelage. C++ is best acquired with a [vetted book](https://stackoverflow.com/q/388242/817643). Reading random code or following other half-baked tutorials can leave one confused. – StoryTeller - Unslander Monica Sep 22 '21 at 15:00
  • C++ allows to overload operators like `+` or `-` and, guess, comparison operators like `==` or as you found `<`. What you see there is the syntax for (here member function variant, it's possible to have free-standing operators as well, which usually is preferrable). – Aconcagua Sep 22 '21 at 15:00
  • *the first line, initialize variables, is easy to grasp* The first line **declares** member variables for Task instances. They are not initialized. To do that: `int value = -1, time = 0, deadline = 999;` – Eljay Sep 22 '21 at 15:23

2 Answers2

2

What you observe is called operator overloading. In this case the operator< is overloaded for class Task.

This is done in order to be able to write something like this.

Task t1{1,2,3};
Task t2{2,3,4};
if(t1 < t2) //note, the operator<  is called
{
    //do your thing
}
Karen Baghdasaryan
  • 2,407
  • 6
  • 24
0

To add to the answer, I would like to point out that the variables are not initialized (in traditional sense). It is so called default initialization or, rather, a lack of initialization as the variables will be of whatever value that happened to be in the memory at that time.

To zero-initialize the array, you'll need to use the following syntax (that resembles calling a default constructor of an array)

struct Task{
    int value, time, deadline;

    bool operator < (const Task& t1) const {
        return deadline < t1.deadline;
    }
} task[1000]{};

...Well, it's simple in your case, since you don't have any user-declared constructors, but in other cases it may become tricky. Read this if you're interested value-initialization.

(And {} is a new syntax for constructing objects introduced in C++11. The prior syntax () has several issues: it does not check that arguments are narrowed, and it suffers from the most vexing parse problem, when Foo aVariable(std::string("bar")); is parsed as function declaration (see).)

IS3NY
  • 43
  • 1
  • 5