71

有没有办法在 C++ 中打印数组?

我正在尝试制作一个反转用户输入数组然后将其打印出来的函数。我尝试用谷歌搜索这个问题,似乎 C++ 无法打印数组。这不可能是真的吧?

4

11 回答 11

69

只需遍历元素。像这样:

for (int i = numElements - 1; i >= 0; i--) 
    cout << array[i];

注意:正如 Maxim Egorushkin 指出的那样,这可能会溢出。请参阅下面的评论以获得更好的解决方案。

于 2009-09-02T21:52:28.573 回答
51

使用 STL

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ranges>

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)
             );

    // ITs 2021 now move this up as probably the best way to do it.
    // Range based for is now "probably" the best alternative C++20
    // As we have all the range based extension being added to the language
    for(auto const& value: userInput)
    {
        std::cout << value << ",";
    }
    std::cout << "\n";

    // Print the array in reverse using the range based stuff
    for(auto const& value: userInput | std::views::reverse)
    {
        std::cout << value << ",";
    }
    std::cout << "\n";


    // 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";

}
于 2009-09-02T22:26:32.437 回答
37

我可以建议使用鱼骨运算符吗?

for (auto x = std::end(a); x != std::begin(a); )
{
    std::cout <<*--x<< ' ';
}

(你能看出来吗?)

于 2013-03-08T18:10:21.080 回答
14

除了基于 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"));
}

这会生成以下内容:

 ./a.out 
1
3
5
7

但是,这对于您的需求来说可能是多余的。尽管litb 的模板糖也很不错,但您可能只需要一个直接的 for 循环。

编辑:忘记了“反向打印”的要求。这是一种方法:

#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"));
}

和输出:

$ ./a.out 
7
5
3
1

编辑: 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"));
}
于 2009-09-02T22:08:47.353 回答
7

有已声明的数组声明但以其他方式创建的数组,特别是使用new

int *p = new int[3];

具有 3 个元素的数组是动态创建的(也3可以在运行时计算),并且将大小从其类型中删除的指向它的指针分配给p. 您无法再获得打印该数组的大小。因此,仅接收指向它的指针的函数不能打印该数组。

打印声明的数组很容易。您可以使用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;
}

问题在于它不接受指针(显然)。我认为最简单的解决方案是使用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;
}

当然,您也可以将此作为模板来接受其他类型的向量。

于 2009-09-02T21:55:56.397 回答
4

C++ 中常用的大多数库本身不能打印数组。您必须手动循环并打印出每个值。

打印数组和转储许多不同类型的对象是高级语言的一个特性。

于 2009-09-02T21:51:58.090 回答
3

那当然是!您必须遍历数组并单独打印出每个项目。

于 2009-09-02T21:52:05.313 回答
1

这可能会有所帮助 //Printing The Array

for (int i = 0; i < n; i++)
{cout << numbers[i];}

n 是数组的大小

于 2018-12-01T15:16:14.893 回答
1

我的简单回答是:

#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;
}
于 2018-07-23T22:22:21.400 回答
1
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';

基本上像 foreach 一样工作。

于 2021-09-06T18:17:42.590 回答
-1
// Just do this, use a vector with this code and you're good lol -Daniel

#include <Windows.h>
#include <iostream>
#include <vector>

using namespace std;


int main()
{

    std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
    
    if (arry.size() != arry.size() || arry.empty()) {
        printf("what happened to the array lol\n ");
        system("PAUSE");
    }
    for (int i = 0; i < arry.size(); i++)
    {   
        if (arry.max_size() == true) {
            cout << "Max size of array reached!";
        }
        cout << "Array Value " << i << " = " << arry.at(i) << endl;
            
    }
}
于 2021-01-04T09:17:53.697 回答