Data Structure: struct - What is it, what is it for and how to use it?

In this tutorial, we will begin the study of data structures, in C++.

Data Abstraction

One of the most important concepts in Computer Science is that of data abstraction. Also called ADT, abstract data type.

Abstraction, in computing, refers to a model of something, a prototype, a generalization of something.

For example, Human is an abstraction. You don't know a Human, you actually know specific people, like your father, your mother, your friends. Humans is a 'mold', to represent an object that has a head, brain, heart, lung, etc.

The same goes for Carro. You don't come to the dealership and say 'I want a car'.
You say: I want a Corolla, a Civic, a Honda Fit, etc.

Car is a generalization of a thing that has all, engine, gear etc.

Well, the same happens in our dear and beloved programming, it is super common in a project to create our abstractions, to represent 'things' of the system that we are going to implement.

Data Structures: structs

So far, we have used very specific data types, such as int, double and float (to work with numbers) or char, to work with characters, for example.

Through arrays, we can create and work with any number of these types of data in a very easy and powerful way.

However, there is a problem. The data types of an array are always the same. You can't have an array that has an integer inside representing an employee's age, a string storing the name and a float to store your salary.

Well, that's what structs are for: packaging other types of data, to create your own type of data. Through structs, we can create new types of data.

For example, let's create the data type Car, inside it there is an integer to store the number of doors, a float to store the engine power and a string to store the model name.

Estrutura de Dados em C++

If before we did:
  • int number;
  • float price;
Now let's do:

  • Employee Jose;

That is, we are declaring a variable named 'Jose', which is of type 'Employee'. Yes, type 'Employee', as well as data type int, float, char, etc.

It is a type of data that you created, a necessary abstraction in your project, and this is done through structs! It can contain as many variables as you want and of any type, it can have arrays, pointers, matrix, etc. All of this 'packaged', in a data structure that you have named.

In the next tutorial, we will learn how to create, access and use a struct, in C ++!

No comments:

Post a Comment