Question:
char peremen_t[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
I need to display all elements of an array. I understand that this needs a loop:
for (int i = 0; i < 10; i++) {
qDebug() <<"peremen_t[i] " << peremen_t[i];
}
And what if we add several elements, let's say this:
char peremen_t[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101, 102, 103};
Then how to iterate over all these elements, constantly change the condition i < ...
? Here's the actual question: how to iterate over an array of elements without knowing how many elements there are? 🙂
Answer:
There are several approaches. First, the size of an array can be calculated using the formula sizeof( массива ) / sizeof( элемента массива )
. for instance
for ( size_t i = 0; i < sizeof( peremen_t ) / sizeof( *peremen_t ); i++ )
{
qDebug() <<"peremen_t[i] " << peremen_t[i];
}
Second, you can use a for loop based on a range. If you need the index of the element, you can determine it before the loop. For instance,
size_t i = 0;
for ( auto x : peremen_t )
{
qDebug() <<"peremen_t[" << i << "] " << x;
++i;
}
You can also use an iterator loop. For instance,
#include <iterator>
// ...
size_t i = 0;
for ( auto it = std::begin( peremen_t ); it != std::end( peremen_t ); ++it, ++i )
{
qDebug() <<"peremen_t[" << i << "] " << *it;
}
And finally, you can write a template function that does the required task. For instance,
template <typename T, size_t N>
inline void f( const T ( &peremen_t )[N] )
{
for ( size_t i = 0; i < N; i++ )
{
qDebug() <<"peremen_t[i] " << peremen_t[i];
}
}
In addition, you can use some boundary value in the array. For example, for character arrays, this could be '\0'
, provided that the actual elements of the array cannot contain that character, or some other unique value. For instance,
char peremen_t[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 0 };
// ^^^
for ( size_t i = 0; permen_t[i] != '\0'; i++ )
{
qDebug() <<"peremen_t[i] " << peremen_t[i];
}