본문 바로가기

Programming/C++ Basic

[Basic C++] 12 – Data Structure in C++ : struct

During the next six posts, I will explain about data structures in C++. Consider data structures as a container for various kinds of data in C++. Data elements are strictly separated in C++ under each data type, however, data structures allow you to group different data types under a single name. There are “struct”, “class” and “union” in C++ that help you form data structures. In this post, I am going to talk about a structure.


Table of Contents

1. Definition of a data structure

2. Syntax of structure

3. Pointer to structure


1. Definition of a structure

Let suppose you are going to define each member of your class at Uni. There is various information that can be used to describe each person such as name, age, major, and hobby. Such information is expressed as variables in C++ and you declare them at the beginning of your program like the below example code,

 

Code example 1

#include <string>

int main()
{
    std::string stu1 = "Tom";

    std::string stu1_nationality = "Japan";

    int age_1 = 25;

    std::string stu2 = "Lee";

    std::string stu2_nationality = "UK";

    int age_2 = 27;

    std::string stu3 = "Tanaka";

    std::string stu3_nationality = "Canada";

    int age_3 = 30;    
}

 

There are three students defined in Code example 1 with different data types for different private information, however, this example has two major deficits. First of all, the variables are not related to each other either explicitly or implicitly under one name, thus the data themselves have no collective meaning. Second of all, they can not be managed at the same time, as they have been declared under different data types.

 

Furthermore, what about you have 100 people in the class and you want to change their common information at once? Of course, you can change every single line, but it is a waste of your valuable time. This is where the true necessity of a data structure appears. By using a data structure, you are able to manage the students’ information under one name no matter what their data types are.


2. Syntax of a data structure

The syntax of a data structure uses the keyword "struct" in C++. It is from C and it does not only contain variables with different data types but also functions and other data structures too. A data structure is also a data type such as int, float, and char in C++. It is a user-defined data type, so you can declare a data structure just like other data types. Figure 1 shows the declaration of a data structure.

 

Figure 1 Syntax of a data structure

 

You can declare a data structure with the keyword "struct". Variables declared inside the body are called "members" and instantiated data structures are called "objects". Declaring a data structure needs an identifier and a body but the instantiation is optional. You can instantiate the data structure at the same time as the declaration.

 

The purpose of a data structure is a lot easier if you put it into categorical thinking. We can categorize things in the world under certain kinds. For instance, sedans, trucks, and SUVs are cars. Cars, trains, and aircraft are vehicles. Vehicles. Making data structures is like making a lot of vehicles (under one name); vehicle 1, vehicle 2, and vehicle 3.

 

You can also make a car out of a vehicle inheriting a few common features with some new functions and we call this "inheritance" but I will explain about inheritance in detail next time.

 

Look code example 2. 

 

Code example 2

#include <iostream>
#include <string>

struct student
{
    std::string major;

    std::string school;

    std::string nationality;

    int age;

    int cy; // Class Year

    student() { school = "Osaka Uni"; nationality = "Korean"; };
};

int main()
{
    student Alex;

    Alex.major = "Civil Engineering";

    Alex.age = 26;

    Alex.cy = 2016;

    student Lee;

    Lee.major = "Computer Engineering";

    Lee.age = 20;

    Lee.cy = 2019;

    Lee.nationality = "American";

    student Tanaka;

    Tanaka.major = "Fine Art";

    Tanaka.school = "Kyoto Uni";

    Tanaka.age = 35;

    Tanaka.cy = 2010;

    Tanaka.nationality = "Irish";

    std::cout << Alex.nationality << " " << Alex.school << std::endl;
    std::cout << Lee.nationality << " " << Lee.school << std::endl;
    std::cout << Tanaka.nationality << " " << Tanaka.school << std::endl;
}

Figure 3 Result of code example 2

 

A data structure "student" is declared with five string and int variables inside. The function "student" is called a "constructor" that allows you to initialize variables in the structure. A constructor has the same name with its structure and can be written in several different forms. There will be a more detailed explanation about a constructor at later posts. All you need to know about a constructor is that it initializes variables.

 

Three students (objects) with three different names (like car 1, car 2, and car 3) are declared in the main function and each one of them has different private information. Of course, some of them share common information which was defined by a constructor.

 

The new operator ". (Dot operator)" is used in the example. The dot operator allows you to access the variables inside an object. By using the dot operator, you can assign values to the variables or simply call the stored values. If the constructor of a data structure is not created, some garbage values are assigned to the variables. 


3. Pointer to structure

Like any other data type, a data structure can be pointed by a pointer of its own type. Using a pointer for a complex data structure makes your program more efficient by not copying a large chunk of data on the memory.

 

Code example 3 shows a pointer variable to a data structure and how to access the members in the pointed data structure. The new operator (->) called "Arrow operator" appeared in the example. The arrow operators is a dereference operator. I highly recommend you to get used to the arrow operator because it is frequently used when handling a class too.

 

Code example 3

#include <iostream>
#include <string>

struct student
{
	int age;
	std::string school;
	std::string major;
};

int main()
{
	student *pstu;
	student Tom;
	student Tanaka;

	pstu = &Tom; // pstu points to Tom object.
	std::cout << pstu->age << std::endl; // Age returns a garbege value
	
	Tom.age = 25;
	std::cout << pstu->age << std::endl;

	Tanaka.school = "Cambridge";
	pstu = &Tanaka; // Now pstu points to Tanaka object.
	std::cout << pstu->school << std::endl;
}

 

You can also pass a data structure pointer to a function. The function "initialize" was defined in Code example 4 which changed the values of the member in the "student" structure. Using a pointer to deal with complex data types will make your program more efficient. Always remember that it is you to manage the memory in C++. This is not becuase C++ is laze, but because the language supports a wide range of functions from low level to advance level when it comes to programming.

 

Code example 4

#include <iostream>
#include <string>


struct student
{
	int age;
	std::string school;
	std::string major;
};

void initialize(student *); // function prototype

int main()
{
	student *pstu;
	student Tom;
	student Tanaka;

	pstu = &Tom; // pstu points to Tom object.
	std::cout << pstu->age << std::endl; // Age returns a garbege value
	
	Tom.age = 25;
	std::cout << pstu->age << std::endl;

	Tanaka.school = "Cambridge";
	pstu = &Tanaka; // Now pstu points to Tanaka object.
	std::cout << pstu->school << std::endl;

	initialize(pstu); // structure pointer to function
	std::cout << Tanaka.school << std::endl;
	std::cout << Tanaka.major << std::endl;
}

void initialize(student* pstu)
{
	pstu->age = 1;
	pstu->school = "default";
	pstu->major = "default";
}

4. Structure in Structure (nested structure)

 

As I said a data structrue can contain various kinds of data types, it can also nest other data structures inside. This is reffered to as "Nested Structure". Using a nested structure is a good practice to categorize your data for better data management. Look example 5.

 

Code example 5

#include <iostream>
#include <string>

struct student
{
	struct gpa
	{
		float math;
		float chemistry;
		float physics;
	};

	int age;
	std::string school;
	std::string major;
	struct gpa s_gpa;
};

int main()
{
	student Tom;
	Tom.s_gpa.math = 1.0;
	Tom.s_gpa.chemistry = 3.0;
	Tom.s_gpa.physics = 4.0;
}

A data structrue "student" has another data sturcture "gpa" inside. You can access the member of "gpa" using the dot operator twice through "student".