在 C++ 中打印数组?

发布于 2024-08-04 03:39:12 字数 99 浏览 3 评论 0原文

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

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

Is there a way of printing arrays in 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

看海 2024-08-11 03:39:12

只需迭代元素即可。像这样:

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

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

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.

成熟稳重的好男人 2024-08-11 03:39:12

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

}

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

}
起风了 2024-08-11 03:39:12

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

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

(你能发现吗?)

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

梦里南柯 2024-08-11 03:39:12

除了基于 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

但是,这对于您的需求来说可能有点过分了。一个直接的 for 循环可能就是您所需要的,尽管 litb 的模板糖也相当不错。

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

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

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:

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

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():

#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"));
}
兔姬 2024-08-11 03:39:12

已声明的数组声明但以其他方式创建的数组,特别是使用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;
}

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

There are declared arrays and arrays that are not declared, but otherwise created, particularly using 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.

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:

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:

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.

夕嗳→ 2024-08-11 03:39:12

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

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

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.

Printing arrays and dumping many different kinds of objects is a feature of higher level languages.

笑饮青盏花 2024-08-11 03:39:12

确实是!您必须循环遍历数组并单独打印每个项目。

It certainly is! You'll have to loop through the array and print out each item individually.

失眠症患者 2024-08-11 03:39:12

这可能有帮助
//打印数组

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

n 是数组的大小

This might help
//Printing The Array

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

n is the size of the array

念﹏祤嫣 2024-08-11 03:39:12
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';

工作原理基本上与 foreach 类似。

std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';

Works basically like foreach.

骑趴 2024-08-11 03:39:12

我的简单回答是:

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

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;
}
り繁华旳梦境 2024-08-11 03:39:12

您可以使用反向迭代器反向打印数组:

#include <iostream>

int main() {
    int x[] = {1,2,3,4,5};
    for (auto it = std::rbegin(x); it != std::rend(x); ++it) 
        std::cout << *it;
}

输出

54321

如果您已经反转了数组,则可以分别将 std::rbeginstd::rend 替换为 std::begin/std::end ,向前迭代数组。

You can use reverse iterators to print an array in reverse:

#include <iostream>

int main() {
    int x[] = {1,2,3,4,5};
    for (auto it = std::rbegin(x); it != std::rend(x); ++it) 
        std::cout << *it;
}

output

54321

If you already reversed the array, you can replace std::rbegin and std::rend with std::begin/std::end, respectively, to iterate the array in forward direction.

国际总奸 2024-08-11 03:39:12

将数组的元素复制到合适的输出迭代器非常简单。例如(使用 C++20 作为 Ranges 版本):

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

template<typename T, std::size_t N>
std::ostream& print_array(std::ostream& os, std::array<T,N> const& arr)
{
    std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
    return os;
}

快速演示:

int main()
{
    std::array example{ "zero", "one", "two", "three", };
    print_array(std::cout, example) << '\n';
}

当然,如果我们可以输出任何类型的集合,而不仅仅是数组,那就更有用了:

#include <algorithm>
#include <iterator>
#include <iosfwd>
#include <ranges>

template<std::ranges::input_range R>
std::ostream& print_array(std::ostream& os, R const& arr)
{
    using T = std::ranges::range_value_t<R>;
    std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
    return os;
}

问题提到了反转数组以进行打印。通过使用视图适配器可以轻松实现这一点:

    print_array(std::cout, example | std::views::reverse) << '\n';

It's quite straightforward to copy the array's elements to a suitable output iterator. For example (using C++20 for the Ranges version):

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

template<typename T, std::size_t N>
std::ostream& print_array(std::ostream& os, std::array<T,N> const& arr)
{
    std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
    return os;
}

Quick demo:

int main()
{
    std::array example{ "zero", "one", "two", "three", };
    print_array(std::cout, example) << '\n';
}

Of course it's more useful if we can output any kind of collection, not only arrays:

#include <algorithm>
#include <iterator>
#include <iosfwd>
#include <ranges>

template<std::ranges::input_range R>
std::ostream& print_array(std::ostream& os, R const& arr)
{
    using T = std::ranges::range_value_t<R>;
    std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
    return os;
}

The question mentions reversing the array for printing. That's easily achieved by using a view adapter:

    print_array(std::cout, example | std::views::reverse) << '\n';
睡美人的小仙女 2024-08-11 03:39:12
// 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;
            
    }
}
// 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;
            
    }
}
遥远的绿洲 2024-08-11 03:39:12

如果你想创建一个打印数组中每个元素的函数;

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

上面的函数仅打印数组中的每个元素,而不是逗号等。

您可能想知道“为什么 sizeoff(arr) 除以 4?”。这是因为如果数组中只有一个元素,cpp 会打印 4。

If you want to make a function that prints every single element in an array;

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

You may be wondering "Why sizeoff(arr) divided by 4?". It's because cpp prints 4 if there's only a single element in an array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文