【问题标题】:How do I print the following array to show number 1 - 1000000如何打印以下数组以显示数字 1 - 1000000
【发布时间】:2020-11-10 19:50:09
【问题描述】:

我想初始化一个数组并从 1-1000000 填充它。然后如何打印数组?

#include<iostream>


using namespace std;


const int holder = 1000000;
int main()
{
    int i = 0;
    int nums[holder] = {0};

    for( int i = 0; i < holder; i++)
    {
        nums[i] = i+1;
    }
return 0;
}

【问题讨论】:

  • std::cout 是在 C++ 中打印到控制台的惯用方式。
  • int nums[] = {holder}; 是错误的,它声明了一个数组,其中一个元素初始化为holder 的值。您希望 int nums[holder] = {0}; 声明一个包含 holder 元素的数组。当您进行更改时,您可能会遇到堆栈大小问题。您可以将声明移到 main 之外以使其成为全局或使其成为静态以帮助实现这一点。您可以考虑改用std::vector
  • int nums[] = { holder }; 创建一个元素为 ONE 的数组,其值为holder

标签: c++ arrays printing


【解决方案1】:

这样的事情怎么样:

// First create a vector containing holder elements
std::vector<int> nums(holder);

// Then set each element to the number from 1 to holder, inclusive
std::iota(begin(nums), end(nums), 1);

然后打印它:

// Print each number in the vector, separated by newlines
for (auto num : nums)
{
    std::cout << num << '\n';
}

这个答案的许多部分确实应该成为任何体面的初学者书籍的一部分。唯一的“新”事物是std::iota 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2019-08-26
    相关资源
    最近更新 更多