Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to output the actual array in c++

Tags:

c++

So, I'm beginning C++, with a semi-adequate background of python. In python, you make a list/array like this:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Then, to print the list, with the square brackets included, all you do is:

print x

That would display this:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

How would I do the exact same thing in c++, print the brackets and the elements, in an elegant/clean fashion? NOTE I don't want just the elements of the array, I want the whole array, like this:

{1, 2, 3, 4, 5, 6, 7, 8, 9}

When I use this code to try to print the array, this happens:

input:

#include <iostream>
using namespace std;


int main()
{
    int anArray[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    cout << anArray << endl;

}

The output is where in memory the array is stored in (I think this is so, correct me if I'm wrong):

0x28fedc

As a sidenote, I don't know how to create an array with many different data types, such as integers, strings, and so on, so if someone can enlighten me, that'd be great! Thanks for answering my painstakingly obvious/noobish questions!

like image 512
user2511129 Avatar asked Jun 22 '13 07:06

user2511129


People also ask

Is it possible to return an array in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

Can you directly print an array in C?

This program will let you understand that how to print an array in C. We need to declare & define one array and then loop upto the length of array. At each iteration we shall print one index value of array. We can take this index value from the iteration itself.

Can we print array in C without loop?

Ya, we can. If the array size is fixed, for example if the array's size is 6. Then you can print the values like printf(a[0]) to printf(a[5]).


2 Answers

Inspired by the answers of juanchopanza and Raxman I decided to do a real IO manipulator, which leads to a syntax like:

const char* arr[] = { "hello", "bye" };
std::cout 
    << "Woot, I can has " << print(arr)
    << " and even " << print(std::vector<int> { 1,2,3,42 }, ":") << "!\n";

printing

Woot, I can has { hello, bye } and even { 1:2:3:42 }!

Note

  • it works seamlessly with chained output streaming using operator<< as usual
  • it is fully generic (supporting any container of streamable types)
  • it even allows to pass a delimiter (as an example)
  • with a little more template arguments it could be made so generic as to work with ostream, wostream etc.
  • fun: Since the delimiter can be any streamable 'thing' as well, you could even... use an array as the delimiter:

    std::cout << "or bizarrely: " << print(arr, print(arr)) << "\n";
    

    resulting in the rather weird sample output:

    or bizarrely: { hello{ hello, bye }bye }
    

    Still demonstrates the power of hooking seamlessly into IO streams, if you ask me.

I believe it will not get much more seamless than this, in C++. Of course there is some implementing to do, but as you can see you can leverage full genericity, so you're at once done for any container of streamable types:

#include <iostream>
#include <vector>

namespace manips
{
    template <typename Cont, typename Delim=const char*>
    struct PrintManip { 
        PrintManip(Cont const& v, Delim d = ", ") : _v(v), _d(std::move(d)) { }

        Cont const& _v;
        Delim _d;

        friend std::ostream& operator<<(std::ostream& os, PrintManip const& manip) {
            using namespace std;
            auto f = begin(manip._v), l(end(manip._v)); 

            os << "{ ";
            while (f != l)
                if ((os << *f) && (++f != l))
                    os << manip._d;
            return os << " }";
        }
    };

    template <typename T, typename Delim=const char*> 
    manips::PrintManip<T, Delim> print(T const& deduce, Delim delim = ", ") { 
        return { deduce, std::move(delim) }; 
    }
}

using manips::print;

int main()
{
    const char* arr[] = { "hello", "bye" };
    std::cout 
        << "Woot, I can has " << print(arr)
        << " and even: " << print(std::vector<int> { 1,2,3,42 }, ':') << "!\n"
        << "or bizarrely: " << print(arr, print(arr)) << "\n";
}

See it live at http://ideone.com/E4G9Fp

like image 38
sehe Avatar answered Oct 07 '22 09:10

sehe


You can write a simple helper function to allow you to stream the array to an output stream (including but not limited to std::cout):

#include <iostream>
// print an array to an output stream
// prints to std::cout by default
template <typename T, std::size_t N>
void print_array(const T(&a)[N], std::ostream& o = std::cout)
{
  o << "{";
  for (std::size_t i = 0; i < N-1; ++i)
  {
    o << a[i] << ", ";
  }
  o << a[N-1] << "}\n";
}

where a function template is used in order to deduce both the type and size of the array at compile time. You can use it like this:

#include <fstream>
int main()
{
  int a[] = {1,2,3,4,5};
  print_array(a); // prints {1, 2, 3, 4, 5} to stdout

  std::string sa[] = {"hello", "world"};
  print_array(sa, std::cerr); // prints {hello, world} to stderr

  std::ofstream output("array.txt");
  print_array(a, output); // prints {1, 2, 3, 4, 5} to file array.txt
}

This solution can be trivially generalized to deal with ranges and standard library containers. For even more general approaches, see here.

As for the side note, you cannot do that in C++. An array can only hold objects of one type.

like image 116
juanchopanza Avatar answered Oct 07 '22 08:10

juanchopanza