简体   繁体   English

在 C++ 中打印一个数组?

[英]Printing an array in C++?

Is there a way of printing arrays in C++?有没有办法在C++中打印arrays?

I'm trying to make a function that reverses a user-input array and then prints it out.我正在尝试制作一个 function 来反转用户输入数组,然后将其打印出来。 I tried Googling this problem and it seemed like C++ can't print arrays. That can't be true can it?我尝试用谷歌搜索这个问题,似乎 C++ 无法打印 arrays。这不可能是真的吧?

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.注意:正如 Maxim Egorushkin 指出的,这可能会溢出。 See his comment below for a better solution.请参阅下面的评论以获得更好的解决方案。

Use the STL使用 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";

}

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?) (你能看出来吗?)

Besides the for-loop based solutions, you can also use an ostream_iterator<> .除了基于 for 循环的解决方案,您还可以使用ostream_iterator<> Here's an example that leverages the sample code in the (now retired) SGI STL reference:这是一个利用(现已停用)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 sugar is 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"));
}

There are declared arrays and arrays that are not declared, 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 .用3个元素数组是动态创建的(和3可能在运行时被计算,太),和指向它的指针,其具有从其类型擦除的尺寸被赋值于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.因此,仅接收指向它的指针的函数不能打印该数组。

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.您可以使用sizeof获取它们的大小并将该大小传递给函数,包括指向该数组元素的指针。 But you can also create a template that accepts the array, and deduces its size from its declared type:但是你也可以创建一个接受数组的模板,并从它声明的类型推导出它的大小:

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 .我认为,最简单的解决方案是使用std::vector It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size member function:它是一个动态的、可调整大小的“数组”(具有您对真实数组所期望的语义),它具有一个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.当然,您也可以将其设为接受其他类型向量的模板。

Most of the libraries commonly used in C++ can't print arrays, per se. C++ 中常用的大多数库本身都不能打印数组。 You'll have to loop through it manually and print out each value.您必须手动遍历它并打印出每个值。

Printing arrays and dumping many different kinds of objects is a feature of higher level languages.打印数组和转储许多不同类型的对象是高级语言的一个特性。

It certainly is!那当然是! You'll have to loop through the array and print out each item individually.您必须遍历数组并单独打印出每个项目。

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.我尝试了Google搜索这个问题,似乎C ++无法打印数组。 That can't be true can it?那不是真的吗?

This might help //Printing The Array这可能有助于//打印数组

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

n is the size of the array n 是数组的大小

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;
}
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';

Works basically like foreach.工作原理与 foreach 类似。

In C++, you can simply print an array by:在 C++ 中,您可以通过以下方式简单地打印数组:

for (int i = 0; i < numberOfElements; i++) {
    cout << arr[i] << " ";
}
// 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;
            
    }
}

You can not print an array just by passing it to a function.不能仅通过将数组传递给函数来打印数组。 Because there is no such function in c++.因为c++中没有这样的函数。 Do it like this:像这样做:

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

Or you can use this: https://github.com/gileli121/VectorEx 或者你可以使用这个: https//github.com/gileli121/VectorEx

You can easily display the array with DisplayVector_1d(). 您可以使用DisplayVector_1d()轻松显示数组。 It developed under visual studio 2015. t works only under windows (tested on windows 7 64 bit). 它是在visual studio 2015下开发的。只能在windows下运行(在Windows 7 64位上测试)。

What you are looking in this library is DisplayVector_1d. 你在这个库中看到的是DisplayVector_1d。 I 一世

It will display the array in listview GUI. 它将在listview GUI中显示该数组。 it is like the _ArrayDisplay function in Autoit. 它就像Autoit中的_ArrayDisplay函数。

Here is an example how to use this: 这是一个如何使用它的示例:

// includes.functions
#include <windows.h>

#include "VectorEx\VectorEx.h"
#include "VectorEx\VectorDisplay.h"
using namespace vectorex;
using namespace vectordisplay;


/*
    This example shows how to use display std::vector array datatype
    with vectordisplay::DisplayVector_1d
*/


int main()
{
    std::vector<std::string> stringVector;

    stringVector.push_back("Bob");
    stringVector.push_back("Fob");
    stringVector.push_back("Rob");
    stringVector.push_back("Nob");

    DisplayVector_1d(&stringVector);

    return 0;
}

显示如何在VectorDisplay.h中使用DisplayVector_1d的示例

Note that I just started to work on this project. 请注意,我刚刚开始研究这个项目。 You are welcome to improve the code and fix bugs 欢迎您改进代码并修复错误

If you want to make a function that prints every single element in an array;如果你想制作一个 function 来打印数组中的每个元素;

#include <iostream>
using namespace std;

int myArray[] = {1,2,3,4, 77, 88};

void coutArr(int *arr, int size){
   for(int i=0; i<size/4; i++){
      cout << arr[i] << endl;
   }
}

int main(){
   coutArr(myArray, sizeof(myArray));
}

The function above prints every single element in an array only, not commas etc.上面的 function 仅打印数组中的每个元素,而不是逗号等。

You may be wondering "Why sizeoff(arr) divided by 4?".您可能想知道“为什么 sizeoff(arr) 除以 4?”。 It's because cpp prints 4 if there's only a single element in an array.这是因为如果数组中只有一个元素,cpp 会打印 4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM