在 C++ 中打印数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1370323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing an array in C++?
提问by Botz3000
Is there a way of printing arrays in C++?
有没有办法在 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?
我正在尝试创建一个函数来反转用户输入数组,然后将其打印出来。我尝试谷歌搜索这个问题,似乎 C++ 无法打印数组。那不会是真的吧?
回答by Botz3000
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.
注意:正如 Maxim Egorushkin 指出的,这可能会溢出。请参阅下面的评论以获得更好的解决方案。
回答by Martin York
Use the STL
使用 STL
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
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)
);
// 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";
// Update for C++11
// Range based for is now a good alternative.
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
}
回答by fredoverflow
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?)
(你能看出来吗?)
回答by Void
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:
除了基于 for 循环的解决方案,您还可以使用ostream_iterator<>。这是一个利用(现已停用)SGI STL 参考中的示例代码的示例:
#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 sugaris quite nice, too.
但是,这对于您的需求来说可能有点过头了。一个直接的 for 循环可能就是你所需要的,尽管litb 的模板糖也很不错。
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():
编辑:C++14 更新使用像std::begin()和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"));
}
回答by Johannes Schaub - litb
There are declared arraysand arrays that are notdeclared, but otherwise created, particularly using new
:
有声明的数组和未声明但以其他方式创建的数组,特别是使用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.
具有 3 个元素的数组是动态创建的(也3
可以在运行时计算),并且将大小从其类型中删除的指向它的指针分配给p
. 您无法再获得打印该数组的大小。因此,仅接收指向它的指针的函数不能打印该数组。
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:
打印声明的数组很容易。您可以使用sizeof
获取它们的大小并将该大小传递给函数,包括指向该数组元素的指针。但是你也可以创建一个接受数组的模板,并从它声明的类型推导出它的大小:
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:
问题在于它不会接受指针(显然)。我认为最简单的解决方案是使用std::vector
. 它是一个动态的、可调整大小的“数组”(具有您对真实数组所期望的语义),它具有一个size
成员函数:
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.
当然,您也可以将其设为接受其他类型向量的模板。
回答by Faxwell Mingleton
Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.
C++ 中常用的大多数库本身都不能打印数组。您必须手动遍历它并打印出每个值。
Printing arrays and dumping many different kinds of objects is a feature of higher level languages.
打印数组和转储许多不同类型的对象是高级语言的一个特性。
回答by Andy Mikula
It certainly is! You'll have to loop through the array and print out each item individually.
那当然是!您必须遍历数组并单独打印出每个项目。
回答by Cogwheel
C++ can print whatever you want if you program it to do so. You'll have to go through the array yourself printing each element.
如果您对其进行编程,C++ 可以打印您想要的任何内容。您必须自己遍历数组来打印每个元素。
回答by Arinjoy Pramanik
This might help //Printing The Array
这可能有助于//打印数组
for (int i = 0; i < n; i++)
{cout << numbers[i];}
n is the size of the array
n 是数组的大小
回答by ej8000
My simple answer is:
我的简单回答是:
#include <iostream>
using namespace std;
int main()
{
int data[]{ 1, 2, 7 };
for (int i = sizeof(data) / sizeof(data[0])-1; i >= 0; i--) {
cout << data[i];
}
return 0;
}