Array of structures in C++
Introduction
There are many tutorials about structures and about arrays. In this article I will describe only one particular case: declaring several structures with an array. If you have comments that clarify things, I will be glad to read them.
Creating a structure
Our task is to describe the position of four points in space. More concretely, four squares on a grid.
Each square must have an x and a y coordinate.
struct Point { int x; int y; }; Point squares[4]; // four elements of type Point
Four structures of type Point are created, each of them in the squares array
You can iterate over all the coordinates with a loop
for (int i = 0; i < 4; i++) { std::cout << squares[i].x << std::endl; std::cout << squares[i].y << std::endl; }
You will most likely get a column of eight zeros or eight identical garbage values.
Let us fill the array with values
for (int i = 0; i < 4; i++) { squares[i].x = i; squares[i].y = i+10; }
Searching an array of structures
int s = 11; // We want to check whether there is // the number 11 among the array elements // and where it is, or they are, if there are several. bool Found = false; for (int i = 0; i < 4; i++) { if (squares[i].x == s) { std::cout << squares[i].x << " = " << s << " index is " << i << " x" << std::endl; Found = true; } else if (squares[i].y == s) { std::cout << squares[i].y << " = " << s << " index is " << i << " y" << std::endl; Found = true; } else { continue; } } if (Found == false) { std::cout << s << " is not found" << std::endl; }
Example of use
An array of structures came in handy for me in Tetris:
Tetris in C++ and SFML2
Related articles
The code on this page was run with g++ 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Andrei Olegovich