有什么办法在c ++中输出实际的数组 [英] Is there any way to output the actual array in c++

查看:230
本文介绍了有什么办法在c ++中输出实际的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我开始C + +,半足够的背景的python。在python中,你创建一个如下的列表/数组:

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

这将显示:

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



如何在c ++中做同样的事,和元素,在优雅/干净的方式?注意我不想只是数组的元素,我想要整个数组,如下:

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:

输入:

#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!

推荐答案

你可以写一个简单的帮助函数,让你将数组流传输到输出流(包括但不限于 std :: cout ):

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.

对于旁注,你不能在C ++中做到这一点。数组只能保存一种类型的对象。

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

这篇关于有什么办法在c ++中输出实际的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆