Evgenii Legotckoi
July 8, 2017, 3:31 p.m.

C++ - Tutorial 006. Structures

Одним из первых шагов в построении новых типов данных является организация данных в структуре, объединяющая несколько различных переменных с разными типами данных. Объявления структуры с помощью ключевого слова struct .

Например, объявим структуру Vector , в котором будет храниться указатель на начало массива элементов типа double и переменная с количеством этих элементов.

  1. struct Vector {
  2. int sz; // Number of elements
  3. double elem; // Pointer to elements
  4. };

A variable of type Vector can be declared in the code as follows:

  1. 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.

  1. void vector_init(Vector& v, int s)
  2. {
  3. v.elem = new double[s]; // Allocating memory for an array of elements
  4. v.sz = s;
  5. }

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:

  1. double read_and_sum(int s)
  2. // Reading integers from standard input to return their sum, consider s positive
  3. {
  4. Vector v;
  5. vector_init(v,s); // Allocate memory for s elements for v
  6. for (int i=0; i!=s; ++i)
  7. cin>>v.elem[i]; // Read data into an array of elements
  8.  
  9. double sum = 0;
  10. for (int i=0; i!=s; ++i)
  11. sum+=v.elem[i]; // Summarize all the elements
  12. return sum;
  13. }

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:

  1. void f(Vector v, Vector& rv, Vector pv)
  2. {
  3. int i1 = v.sz; // access through name
  4. int i2 = rv.sz; // access through reference
  5. int i4 = pv−>sz; // access through pointer
  6. }

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html