Question:
char peremen_t[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
I need to output all the elements of an array. I understand that this requires a loop:
for (int i = 0; i < 10; i++) {
qDebug() <<"peremen_t[i] " << peremen_t[i];
}
But what if you add several elements, let's say this:
char peremen_t[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101, 102, 103};
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 range based for loop. If you need the index of the element, you can define 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 a loop with iterators. 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;
}
Finally, you can write a templated function that does the task you want. 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 array elements cannot contain this 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];
}