Одним из первых шагов в построении новых типов данных является организация данных в структуре, объединяющая несколько различных переменных с разными типами данных. Объявления структуры с помощью ключевого слова struct .
Например, объявим структуру Vector , в котором будет храниться указатель на начало массива элементов типа double и переменная с количеством этих элементов.
struct Vector { int sz; // Number of elements double∗ elem; // Pointer to elements };
A variable of type Vector can be declared in the code as follows:
Vector v;
However, this declaration is not useful in itself, since it is necessary to initialize this structure with some array of elements with a given number of elements. We can do this with the following function.
void vector_init(Vector& v, int s) { v.elem = new double[s]; // Allocating memory for an array of elements v.sz = s; }
In this function, a reference to the Vector object and the number of elements that need to initialize this vector are passed as arguments. Since an object of type Vector is passed as a non-constant object, then we can modify it.
The new operator allocates memory in a so-called free storage (dynamic memory or a simple heap).
The simple use of Vector looks like this:
double read_and_sum(int s) // Reading integers from standard input to return their sum, consider s positive { Vector v; vector_init(v,s); // Allocate memory for s elements for v for (int i=0; i!=s; ++i) cin>>v.elem[i]; // Read data into an array of elements double sum = 0; for (int i=0; i!=s; ++i) sum+=v.elem[i]; // Summarize all the elements return sum; }
There is still a long way to go before the Vector becomes flexible and elegant, like a vector from a standard library.
To access the structure elements, you can use the dot ( dot . ) If access using a name or link is used, or -> if access is through a pointer. For example:
void f(Vector v, Vector& rv, Vector∗ pv) { int i1 = v.sz; // access through name int i2 = rv.sz; // access through reference int i4 = pv−>sz; // access through pointer }