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

妖精的绣舞 提交于 2019-12-17 18:43:56

问题


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!


回答1:


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.




回答2:


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




回答3:


for(int i=0;i<9;i++)
cout << anArray[i] << endl;

ahh ok with brackets it be such (simply array print logic for your arrays , u can make it more general in future)

  cout<<'{';
    for(int i=0;i<8;i++)
           cout << anArray[i] <<','; 
    cout<<anArray[8]<<'}';

For python users and c++ lovers there is std::vector .

here how it be print logic for vector //solution with [] operator

if(anVector.size()>=1){
     std::cout<<"{";
      for(int i=0;i<anVector.size()-1;i++){
            std::cout<<anVector[i]<<',' ; 

      }
    std::cout<<anVector[anVector.size()-1]<<'}' ; 
}

//solution with iterator

  std::vector<int>::iterator it =anVector.begin();
       if(it!=anVector.end()){ 
            std::cout << '{'<<*it;
            ++it;
            for (; it != anVector.end(); ++it){
               std::cout<<','<< *it ; 
            }
            std::cout << '}';
        }

Also check C++ 11 std::vector . In new standart initializing and other things more elegant




回答4:


Probably the easiest way to get an array printed nicely (assuming it has a length greater than zero) is with something like:

std::cout << "{" << anArray[0];
for (int i = 1; i < sizeof (anArray) / sizeof (*anArray); i++)
    std::cout << ", " << array[i];
std::cout << "}";

If you wish to be able to print less than the full array, you'll need a way to specify the length (which may be zero so you should handle that case:

if (length == 0)
    std::cout << "{}";
else {
    std::cout << "{" << anArray[0];
    for (int i = 1; i < length; i++)
        std::cout << ", " << array[i];
    std::cout << "}";
}

There may be other variations of that such as printing at a given starting point rather than element zero but I won't go into that here. Suffice to say, it's just a small modification to the loop and if condition.

Of course, if you want to do it the simple way, with std::cout << myvariable;, you can consider wrapping the whole thing in a class and providing your own operator<< for it - that would be a more object-oriented way of doing things.




回答5:


If you don't care too much about having the comma as a separator, you could also use output iterators.

#include <iostream>
#include <iterator>
#include <algorithm>

...

int anArray[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

std::cout << "{ ";
std::copy(anArray, anArray + 9, std::ostream_iterator<int>(std::cout, " "));
std::cout << "}" << std::endl;


来源:https://stackoverflow.com/questions/17248462/is-there-any-way-to-output-the-actual-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!