Printing an array in C++?
Solution 1
Just iterate over the elements. Like this:
for (int i = numElements - 1; i >= 0; i--)
cout << array[i];
Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.
Solution 2
Use the STL
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ranges>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// ITs 2021 now move this up as probably the best way to do it.
// Range based for is now "probably" the best alternative C++20
// As we have all the range based extension being added to the language
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print the array in reverse using the range based stuff
for(auto const& value: userInput | std::views::reverse)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
}
Solution 3
May I suggest using the fish bone operator?
for (auto x = std::end(a); x != std::begin(a); )
{
std::cout <<*--x<< ' ';
}
(Can you spot it?)
Solution 4
Besides the for-loop based solutions, you can also use an ostream_iterator<>. Here's an example that leverages the sample code in the (now retired) SGI STL reference:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
copy(foo,
foo + sizeof(foo) / sizeof(foo[0]),
ostream_iterator<short>(cout, "\n"));
}
This generates the following:
./a.out
1
3
5
7
However, this may be overkill for your needs. A straight for-loop is probably all that you need, although litb's template sugar is quite nice, too.
Edit: Forgot the "printing in reverse" requirement. Here's one way to do it:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
reverse_iterator<short *> end(foo);
copy(begin,
end,
ostream_iterator<short>(cout, "\n"));
}
and the output:
$ ./a.out
7
5
3
1
Edit: C++14 update that simplifies the above code snippets using array iterator functions like std::begin() and std::rbegin():
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
// Generate array iterators using C++14 std::{r}begin()
// and std::{r}end().
// Forward
std::copy(std::begin(foo),
std::end(foo),
std::ostream_iterator<short>(std::cout, "\n"));
// Reverse
std::copy(std::rbegin(foo),
std::rend(foo),
std::ostream_iterator<short>(std::cout, "\n"));
}
Solution 5
There are declared arrays and arrays that are not declared, but otherwise created, particularly using new
:
int *p = new int[3];
That array with 3 elements is created dynamically (and that 3
could have been calculated at runtime, too), and a pointer to it which has the size erased from its type is assigned to p
. You cannot get the size anymore to print that array. A function that only receives the pointer to it can thus not print that array.
Printing declared arrays is easy. You can use sizeof
to get their size and pass that size along to the function including a pointer to that array's elements. But you can also create a template that accepts the array, and deduces its size from its declared type:
template<typename Type, int Size>
void print(Type const(& array)[Size]) {
for(int i=0; i<Size; i++)
std::cout << array[i] << std::endl;
}
The problem with this is that it won't accept pointers (obviously). The easiest solution, I think, is to use std::vector
. It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size
member function:
void print(std::vector<int> const &v) {
std::vector<int>::size_type i;
for(i = 0; i<v.size(); i++)
std::cout << v[i] << std::endl;
}
You can, of course, also make this a template to accept vectors of other types.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on July 05, 2022Comments
-
Admin almost 2 years
Is there a way of printing arrays in C++?
I'm trying to make a function that reverses a user-input array and then prints it out. I tried Googling this problem and it seemed like C++ can't print arrays. That can't be true can it?
-
P Shved almost 15 yearsI'd also like to note, that in C++ world you mostly don't create a new, reversed array and then print it. Instead, you usually iterate the array in the other way: for (i = numElements-1; i>=0; i--) cout << array[i] << ",";
-
Martin York almost 15 yearsYou can do it one statement in C++. I don't see this as a missing feature as using iterators makes it so much more powerful. Now I can abstract away where I am printing: it does not matter if the destination is console, pipe, file, another container, a function, a DB. It all looks and behaves the same.
-
Martin York almost 15 yearsstandard algorithms dont require a loop. (though thay may use one internally).
-
Andy Mikula almost 15 yearsWhat if I don't have access to the STL?
-
Steve Jessop almost 15 yearsThen you aren't using C++. Perhaps you're using Symbian/C++, or some subset of C++ provided by an embedded compiler. (Granted that technically, the STL is a precursor to the standard libraries in standard C++. But usually when people say "STL", they mean "the class and function templates in the C++ standard libraries", not the pre-standard STL. Hence STL is a subset of C++).
-
Steve Jessop almost 15 yearsWhat, no std::copy_n to an ostream_iterator? ;-)
-
Admin over 12 yearsthis I just ran this on gcc 4.6.1 using g++..it does not work
-
Sam Stoelinga over 10 yearsJust wondering whether there is any speed advantage with this approach?
-
Martin York over 10 years@SamStoelinga: In speed terms. Always measure. I would use this for readability (thus maintainability). But iterators on vectors have always been considered very efficient so its not a worry I would really consider in most situations (unless speed was critical).
-
Maxim Egorushkin about 8 yearsThis version might overflow
int
, since the number of elements issize_t
. Robust version is even more elegant:for(size_t i = numElements; i--;)
-
Botz3000 about 8 years@MaximEgorushkin I see your point, your solution seems to be the best way to do it.
-
Nic3500 almost 6 yearsExplaining your code, and how it responds to the question, would greatly increase the quality of this answer.
-
ej8000 almost 6 yearsThe code is self-explanatory it reverses an array and print it as elements
-
ej8000 almost 6 yearsthe output is 721
-
MartianMartian over 5 yearsfor(auto x: someArray){cout<<x<<endl;};
-
Lightness Races in Orbit over 5 years@Martian2049 Not equivalent.
-
Lightness Races in Orbit over 5 years@Steve "Then you aren't using C++" Not necessarily so. A freestanding implementation is explicitly permitted to omit all but a small collection of standard headers, and none of those mandated contains functionality inherited from the STL. Further reading
-
YLR over 3 yearsCould tou give more details with your code, some explanation will be welcome ;)