Lesson # 9. Structures

Theory

Structures in C++

  • A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths.
    • Example:

      1
      2
      3
      4
      5
      6
      7
      
      struct product {
        int weight;
        double price;
      } ;
       
      product apple;
      product banana, melon;
      This declares a structure type, called product, and defines it having two members: weight and price, each of a different fundamental type. This declaration creates a new type (product), which is then used to declare three objects (variables) of this type: apple, banana, and melon. Note how once product is declared, it is used just like any other type.
    • Right at the end of the struct definition, and before the ending semicolon (;), the optional field object_names can be used to directly declare objects of the structure type. For example, the structure objects apple, banana, and melon can be declared at the moment the data structure type is defined:
    • 1
      2
      3
      4
      
      struct product {
        int weight;
        double price;
      } apple, banana, melon;
      In this case, where object_names are specified, the type name (product) becomes optional: struct requires either a type_name or at least one name in object_names, but not necessarily both.

    Access to the objects’ members

  • Once the three objects of a determined structure type are declared (apple, banana, and melon) its members can be accessed directly. The dot notation is used. Dot (.) must be inserted between the object name and the member name. For example, we could operate with any of these elements as if they were standard variables of their respective types:
  • 1
    2
    3
    4
    5
    6
    
    apple.weight
    apple.price
    banana.weight
    banana.price
    melon.weight
    melon.price
    Each one of these has the data type corresponding to the member they refer to: apple.weight, banana.weight, and melon.weight are of type int, while apple.price, banana.price, and melon.price are of type double.

    Pointers to structures

  • Structures can be pointed to by its own type of pointers:
  • 1
    2
    3
    4
    5
    6
    7
    
    struct Product_t {
      int weight;
      double price;
    } apple, banana, melon;
     
    Product_t aproduct;
    Product_t * pproduct;
    Here aproduct is an object of structure type Product_t, and pproduct is a pointer to point to objects of structure type Product_t.
  • Therefore, the following code would also be valid:
  •  
    pproduct = &aproduct;
    
    The value of the pointer pproduct would be assigned the address of object aproduct.
  • The following example serve to introduce a new operator: the arrow operator (->):
  • //...
    struct Product_t {
      int weight;
      double price;
    } ;
     
    int main ()
    {
      string mystr;
     
      Product_t aproduct;
      Product_t * pproduct;
      pproduct = &aproduct;
     
      cout << "Enter weight: ";
      cin >> pproduct ->weight;
      cout << "Enter price: ";
      cin >> pproduct ->price;
     
      cout << "\nYou have entered:\n";
      cout << pproduct ->weight << " ";
      cout << pproduct ->price;
     
      return 0;
    }

    Tuples

  • A tuple is an object that can hold a collection of items. Each item can be of a different type.
  • Example:

    #include <string>
    #include <tuple> // std::tuple, std::get, std::tie, std::ignore
     
    using namespace std;
     
    int main()
    {
      tuple<int, char, string> t {4, 'z', "C++"}; // the 1-st way of declaration
      auto x = make_tuple(4, 'z', "C++"); // the 2-d way of declaration
     
      auto s1 = get<2>(x);  // access element
      get<0>(t) = 20; // set to another value
      int i; char c; string s;
      tie(i, c, s) = t; // unpack elements
      tie(ignore, ignore, s) = t; //unpack (with ignore) 
    }

    Labs and tasks

    Lab 1:
    To do: Create a Books_t structure to store data about books. Add the following properties (members) of the object:

    • book’s title
    • year of work

    Tasks:

    1. Create a Books_t structure
    2. Implement a method for printing out the information about the objects:
    3. void printBook(Books_t book);
    4. Specify two object names (e.g. Pushkin, Chekhov).
    5. In the main program, create at least 2 objects, display summaries of those books.

    Expected output:

    Lab 1:
    Enter year of Chekhov work Three Sisters:
    1897
    Pushkin's work is:
     Eugene Onegin 1823
    And Chekhov's:
     Three Sisters 1897
    

    ✍ How to do:

    • To perform the lab, create an empty console application with a name Lesson8. Add files: main8.cpp, structBooks8.cpp, structBooks8.h.
    • Include all the necessary libraries and files.
    • 1. Create a Books_t structure to store data about books. Add the following properties (members) of an object: book’s title, year of work.

    • The structure must be defined inside a header file. So, open the structBooks8.h and add the code to define the structure with two members, they are title and year:
    • struct Books_t
      {
      	string title;
      	int year;
      };
      

      2. Implement a method to print out the information about the objects.

    • Also, inside the header file, you should define the method with a parameter of the Books_t type, to accept a specific book from the main program. Add the code after the structure:
    • //method for printing out the information about the objects
      void printBook(Books_t book);
      
    • The implementation of the function must be placed into the structBooks8.cpp file:
    • void printBook(Books_t book)
      {
      	cout << book.title;
      	cout << " " << book.year << endl;
      }
      

      3. Specify two objects (e.g. Pushkin, Chekhov).

    • Open the main.cpp file and inside the main function add the code to create two objects of the structure type:
    • Books_t Pushkin;
      Books_t Chekhov;
      

      4. In the main program, create at least 2 books, display summaries on these books.

    • After the objects' definitions, add the code to initialise the members (fields) with specific values. Ask user to enter one of the fields value, e.g. the year of the book:
    • Pushkin.title = "Eugene Onegin";
      Pushkin.year = 1823;
      
      Chekhov.title = "Three Sisters";
      cout << "Enter year of Chekhov work Three Sisters: "<cin >> Chekhov.year;
      
    • Print information about the books using the printBook method:
    • cout << "Pushkin's work is:\n ";
      printBook(Pushkin);
      cout << "And Chekhov's:\n ";
      printBook(Chekhov);
      
      system("pause");
      
    • Add the code to return a value 0 inside the main function. Run the program and check the output.
    Task 1:

    To do: Create a Cars_t structure to store information about cars. Add members (fields) about the car's color, car's brand and year of issue. Create at least 4 objects and output information about those objects, using a printCars method.

    Note: The signature of the printCars method should be as follows:

    void printCars(Cars_t car);

    Expected output:

    Task 1:
    Enter car's brand:
    >>audi
    Enter car's color:
    >>grey
    Enter car's year of issue:
    >>1997
    Summary info:
    audi grey 1997
    bmw green 2009
    suzuki white 2015
    honda black 2019
    

    [Solution and Project name: Lesson_9task1, file name L9Task1main.cpp, L9Task1imp.cpp, L9Task1.h]

    Lab 2, arrays of structure type:

    To do: Create a Toys_t structure to store data about toys for sale. Add following properties (members) of the object:

    • toy's title of string type
    • age of children to play with that toy (integer type)

    Tasks:

    1. Implement a method for printing out the information about the objects:
    2. void printBook(Toys_t toy);
    3. Implement a method for printing out the toys for small children (up to 4 years old):
    4. void printToy4(Toys_t toy);
    5. Specify an array of objects toys. Since structures are types, they can also be used as a type of arrays to construct tables or databases of them.
    6. In the main program, create at least 4 elements of the array, display summaries on those toys.

    Expected output:

    Enter toy's title:
    >>cat
    Enter child's age:
    >>2
    Summary info:
    car 3
    doll 4
    crocodile 6
    cat 2
    Summary info for small children:
    car 3
    doll 4
    cat 2
    

    ✍ How to do:

    • To perform the lab create an empty console application with a name Lesson9Toys. Add files: main9.cpp, structToys9.cpp, structToys9.h.
    • Include all needed libraries into the code of those files.
    • 1. Create a Toys_t structure for storing data about the toys for sale

    • The structure must be defined inside a header file. So, open the structToys8.h and add the code to define the structure with two properties (members), they are title and age:
    • struct Toys_t
      {
      	string title;
      	int age;
      };
      

      2. Implement a method to print out information about the objects.

    • Also inside the header file you should define a method with a parameter of Toys_t type, to accept a specific toy from the main program. Add the code after the structure:
    • //method for printing out the information about the objects
      void printToys(Toys_t toy);
      
    • The implementation of the function should be placed into the structToys8.cpp file:
    • void printToys(Toys_t toy)
      {
      	cout << toy.title;
      	cout << " " << toy.age << endl;
      }
      

      3. Implement a method to print out the toys for small children (up to 4 years old)

    • Inside the header file, define a method with a parameter of Toys_t type:
    • //method to print out the toys for small children
      void printToy4(Toys_t toy);
      
    • The implementation of the function should be placed into the structToys8.cpp file:
    • void printToy4(Toys_t toy)
      {
      	if (toy.age <= 4) {
      		printToys(toy);
      	}
      }
      

      4. Specify an array of objects toys.

    • Open the main.cpp file and inside the main function add the code to create an array of objects of structure type:
    • Toys_t toys[4];
      

      5. In the main program, create at least 4 elements of the array, display summaries on those toys.

    • After the objects' definitions, add the code to initialise members (fields) with specific values. Ask user to enter the values of one array element:
    • toys[0].title = "car";
      toys[0].age = 3;
      toys[1].title = "doll";
      toys[1].age = 4;
      toys[2].title = "crocodile";
      toys[2].age = 6;
      cout << "Enter toy's title: " << endl;
      cin >> toys[3].title;
      cout << "Enter child's age: " << endl;
      cin >> toys[3].age;
      
    • Print out the information about the toys using the printToys method, and information about the toys for small children:
    • cout << "Summary info:\n ";
      for (auto x: toys)
      	printToys(x);
      cout << "Summary info for small children:\n ";
      for (auto x : toys)
      	printToy4(x);
      
      system("pause");
      
    • Add the code to return a value 0 inside the main function. Run the program and check the output.
    Task 2:

    To do: Create a Tours_t structure to store information about tours for tourists. Add members (fields) to implement the following info about the tour: country name, number of people, number of days, country rate (of double type). Create a method to print the data, as well as method of the structure to calculate the cost of a trip based on: number of people * number of days * country rate. Inside the main function, specify an array of objects tours. Both methods must be called for the array elements.

    Note: The signature of the printTourCost method should be as follows:

    // returnes the result of calculation, double type
    double printTourCost(Tours_t tour);

    Expected output:

    Task 2:
    Summary info:
     Sweden: people 2, days 3, rate 155.5
     the price is 933
    Norway: people 1, days 3, rate 265.5
     the price is 796.5
    UK: people 2, days 4, rate 455.5
     the price is 3644
    

    [Solution and Project name: Lesson_9task2, file names L9Task2main.cpp, L9Task2imp.cpp, L9Task2.h]

    Lab 3, Pointers to structures:

    To do: Create a Movies_t structure for storing data about movies. Add the following properties (members) of an object:

    • movie's title of string type
    • the year of issue (integer type)

    Specify an array of movies (ask user to enter the info of one film). Implement a method for printing out information about the objects, use a pointer to those objects and an arrow operator.

    Expected output:

    Please, enter a title: 
    >>Matrix
    Please, enter year: 
    >>1999
    
    Summary information:
    Matrix 1999
    Titanic 1997
    

    ✍ How to do:

    • To perform the lab create an empty console application named Lesson8Movies. Add files: mainMovies9.cpp, structMovies9.cpp, structMovies9.h.
    • Include all necessary libraries into code of those files.
    • A structure must be defined inside a header file. So, open the structMovies9.h and add the code to define a structure with two properties (members), they are title and year:
    • struct Movies_t {
      	string title;
      	int year;
      };
      
    • Also, inside the header file, you should define a method with a parameter of Movies_t type, to accept an array of movies from the main program. Add the code after the structure:
    • //method for printing out the information about the movies array with n elements
      void printMovies(Movies_t* movie, int n);
      
    • Implementation of the function should be placed into structMovies9.cpp implementation file:
    • void printMovies(Movies_t* array, int n) {
      	Movies_t *ptr = array;
      	for (int i = 0; i < 2; i++) {
      		cout << ptr->title << " " << ptr->year << endl;
      		ptr++;
      	}
      }
      
      *ptr is a pointer to point at location which *array pointer points at.
      The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members. This operator serves to access a member of an object directly from its address.
    • Open the mainMovies9.cpp file and inside the main function add the code to create an array of objects of structure type and a pointer to point at that array:
    • Movies_t amovie[3];
      Movies_t * pmovie;
      
      pmovie = amovie;
      
    • After the objects' definitions, add the code to initialise properties (fields) with specific values. Ask user to enter the values of one array element:
    • amovie[1].title = "Titanic";
      amovie[1].year = 1997;
      cout << "Enter title: ";
      cin >> pmovie->title;
      cout << "Enter year: ";
      cin >> pmovie->year;
      
    • Print out the information about the movies using the printMovies method:
    • cout << "\nThe summary:\n";
      printMovies(amovie, 2);
      
      system("pause");
      
    • Inside the main function, add the code to return a value 0. Run the program and check the output.
    Task 3:

    To do: Create an Employee_t structure to store information about employees of some company. Add members (fields) to implement the following info about the employees: name, department, phone, salary. Specify an array of employees. Implement a method for printing out the information about the objects, use pointer to those objects and arrow operator. Also, create a smallSalary method to print out information about the employees, whose salary is less than 30 000 roubles.

    Note: A signature of the smallSalary method should be as follows:

    void smallSalary(Employee_t* array, int n);

    Expected output:

    Task 3:
    Summary info:
    Ivanov: bookkeeping department, t. 233-33-33, 28000 roubles
    Petrov: IT department, t. 233-33-34, 45000 roubles
    Sidorov: client department, t. 233-33-35, 25000 roubles
    
    Salary is less than 30 000 roubles:
    Ivanov
    Sidorov
    

    [Solution and Project name: Lesson_9task3, file names L9Task3main.cpp, L9Task3imp.cpp, L9Task3.h]


    Tuples

    Task 4:

    To do: Declare a tuple mytuple of two elements, they are a number (5) and a character ('a') (think about their type). Perform the following tasks:

  • Change the value of the first element to 6
  • Unpack elemetns and print them
  • Expected output:

    Task 4:
    mytuple contains: 6 and a
    

    [Solution and Project name: Lesson_9task4, file names L9Task4main.cpp]