← C++ from Scratch Lesson 23 of 62 · 10 XP

Structs

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

struct gathers different pieces of data into one type:

struct Item {
    std::string name;
    int price;
    int count = 1;          // a default value
};

Item potion{"Potion", 25, 3};   // in the order of the fields
potion.count += 2;              // access a field with a dot
Item items[2] = {{"Sword", 100}, {"Shield", 80}};

A struct is easy to pass to a function as a whole and to return from it. In C++ struct and class are almost the same thing — the only difference is the default access (module 5).

Task. Read n, then n lines of name price count. Print the name of the item with the largest total value (price × count) and that value, separated by a space. If there's a tie, print the first of them.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.