@schorsch312's answer is correct, but the suggestion to have the print()
function take an std::vector
is not the "C++ way": Using std::vector
instead of a plain array in your main program is just fine, but when writing a function - I would recommend not to take a type more specific than what you actually need to perform the function's work, and specifically not allocate memory on the heap with a new vector.
For the case of you having a C array in your program, @Bathsheba's suggestion of a print()
is better in my opinion, in that it will allow you to pass the array as-such, and thus iterate over it properly.
However - for pedagogical reasons, I would suggest you consider this version print()
:
template <std::size_t N>
void print(const int (&arr)[N]) {
for(auto i : arr) {
std::cout << i << " ";
}
}
which illustrates how print()
can take an array reference. You need the template when you don't know the array size apriori. (and this also works of course.)
Alternatively, you could use the standard library algorithm, std::for_each
, like so:
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
int arr[] {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5};
for(auto i:arr) {
std::cout << i << ' ';
}
std::cout << '\n';
std::for_each(
std::begin(arr), std::end(arr),
[](auto i) { std::cout << i << ' '; }
);
}
Note that when you use the ranged-for loop, what happens is basically the equivalent of the for_each
invocation, or of a raw for loop over an iterator beginning at std::begin(arr)
and ending at std::end(arr)
.
Yet another alternative - which does not require concerning yourself with iterator pairs - is to have a print()
function taking a span
(What is a "span" and when should I use one?). Here it makes some sense since a plain C array can be referred to by a span: It has contiguous element storage and a specific length. If you were to be using C++20, your span-using print function would look like this:
#include <span>
void print(const std::span<int> &sp) {
for(auto i : sp) {
std::cout << i << ' ';
}
}
and again you don't have to specify the length in your main function. C++14 doesn't have spans in the standard library, but the C++ Guidelines Support Library (see here or here) has it, as gsl::span
- and it works in C++14.
Nitpicks:
- There is no need to
return 0
from main()
- that happens automatically.
- Please use spaces between
#include
directives and the angle-brackets (i.e. #include <foo>
, not #include <foo>
.
- Please use spaces before and after
<<
operators.
- To print a space, you don't need a string; the single space character suffices, i.e.
std::cout << ' '
rather than std::cout << " "
.