Modern
C++
can be quite expressive:
#include <iostream>
#include <string>
#include <array>
using namespace std;
template <typename T, size_t N> void show_array( array <T,N> & a)
{
for (const auto & x : a) cout << x << endl;
}
int main()
{
array<int,3> ai = { -3 ,17, 0};
array<string,2> as= {"foo", "bar"};
show_array(ai);
show_array(as);
}
A more (more) traditional approach:
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
void show_int_array(int ai[], size_t size)
{
for (size_t n = 0; n < size; ++n)
cout << ai[n] << endl;
}
void show_string_array(string as[], size_t size)
{
for (size_t n = 0; n < size; ++n)
cout << as[n] << endl;
}
int main()
{
int ai[] = {3, -5, 7};
string as[] = { "foo", "bar" };
show_int_array(ai, sizeof(ai)/sizeof(ai[0]));
show_string_array(as, sizeof(as)/sizeof(as[0]));
}
The code redundancy of
show_int_array
and
show_string_array
immediately suggests the usage of a template:
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
template <typename T> void show_array(T a[], size_t size)
{
for (size_t n = 0; n < size; ++n)
cout << a[n] << endl;
}
int main()
{
int ai[] = {3, -5, 7};
string as[] = { "foo", "bar" };
show_array(ai, sizeof(ai)/sizeof(ai[0]));
show_array(as, sizeof(as)/sizeof(as[0]));
}
'Minimalist' approach
#include <iostream>
#include <string>
using namespace std;
int main()
{
int ai[] = {3, -5, 7};
string as[] = { "foo", "bar" };
for (auto x : ai) cout << x << endl;
for (auto s : as) cout << s << endl;
}