Tuesday 15 July 2014

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


So, I'm starting C ++, in Python with a semi-sufficient background of the dragon, List / ARLs create:

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

Again, To print the list, which contains square brackets, you do everything:

  print x   

this will be displayed: < How do I do the exact same thing in C ++, an elegant / In clean fashion, brackets And print elements? Note: I just do not want elements of array, I want the whole array, like:

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

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

Input:

  #include & lt ; Iostream & gt; using namespace std; Int main () {int anArray [9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Cout & lt; & Lt; AnArray & lt; & Lt; Endl; }   

is the output where the array is stored in the memory (I think it is like this, correct me if I am wrong):

  0x28fedc As a sidenote, I do not know how to create an array of many different data types, such as integers, strings, and so on, so if someone can illuminate me, then 'be great! Thank you for answering my palliative / noobish questions!   

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

  #include & lt; Iostream & gt; // Print an array to an output stream / print by default template on std :: cout & lt; Typename T, std :: size_t N & gt; Zero print_are (Constt T (And A) [N], Stud :: Ostream and O = Study :: COT) {O & Lt; & Lt; "{"; For  & Lt; "} \ N"; }   

Where a function template is used to extract the type and size of the array at compile time. You can use it like this:

  #include & lt; Fstream & gt; Int main () {int a [] = {1,2,3,4,5}; Print_array (a); // {1, 2, 3, 4, 5} stdout std :: string sa to print {] "Hello", "world"}; Print_array (SA, STD :: CRR); // print {hello, world} stderr std :: ofstream output ("array.txt"); Print_array (a, output); // {1, 2, 3, 4, 5}} to print the array1xt file   

This solution can be generalized to deal with trivial and standard library containers more general For ways, see.

For side-note, you can not do it in C ++ An array can hold only one type of objects.

No comments:

Post a Comment