C++ 将 int 数组从零填充到定义的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4803898/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:33:50  来源:igfitidea点击:

Fill in the int array from zero to defined number

c++arrays

提问by Radek Simko

i need to fill in the int[] array in C++ from zero to number defined by variable, but ISO C++ forbids variable length array... How to easily fill in the array? Do i need to allocate/free the memory?

我需要在 C++ 中将 int[] 数组从零填充到变量定义的数字,但是 ISO C++ 禁止变长数组......如何轻松填充数组?我需要分配/释放内存吗?

int possibilities[SIZE];
unsigned int i = 0;
for (i = 0; i < SIZE; i++) {
    possibilities[i] = i;
}

btw. if you would ask - Yes, i need exactly standard int[] arrays, no vectors, no maps etc.

顺便提一句。如果你问 - 是的,我需要完全标准的 int[] 数组,没有向量,没有地图等。

回答by jarno

In c++11 you can use std::iota and std::array. Example below fills array sized 10 with values from 1 to 10.

在 c++11 中,您可以使用 std::iota 和 std::array。下面的示例用 1 到 10 的值填充大小为 10 的数组。

std::array<int, 10> a;
std::iota(a.begin(), a.end(), 1);

EditNaturally std::iota works with vectors as well.

编辑自然 std::iota 也适用于向量。

回答by Oliver Charlesworth

As you've found, you cannot create a variable-length array on the stack. So your choices are either to allocate it on the heap (introduces memory-management issues), or to use a std::vectorinstead of a C-style array:

正如您所发现的,您无法在堆栈上创建可变长度数组。所以你的选择要么是在堆上分配它(引入内存管理问题),要么使用 astd::vector而不是 C 风格的数组:

std::vector<int> possibilities(SIZE);
for (int i = 0; i < SIZE; i++)
{
    possibilities[i] = i;
}

If you want to get even more flashy, you can use STL to generate this sequence for you:

如果你想变得更加华丽,你可以使用 STL 为你生成这个序列:

// This is a "functor", a class object that acts like a function with state
class IncrementingSequence
{
public:
    // Constructor, just set counter to 0
    IncrementingSequence() : i_(0) {}
    // Return an incrementing number
    int operator() () { return i_++; }
private:
    int i_;
}

std::vector<int> possibilities(SIZE);
// This calls IncrementingSequence::operator() for each element in the vector,
// and assigns the result to the element
std::generate(possibilities.begin(), possibilities.end(), IncrementingSequence);

回答by kalaxy

If you have access to boost then you already have access to an incrementing iterator.

如果您可以访问 boost,那么您已经可以访问递增迭代器。

#include <vector>
#include <boost/iterator/counting_iterator.hpp>

std::vector<int> possibilities(
    boost::counting_iterator<int>(0),
    boost::counting_iterator<int>(SIZE));

The counting iteratoressentially wraps incrementing a value. So you can automatically tell it the begin and end values and vector will populate itself properly.

计数迭代本质包装递增值。所以你可以自动告诉它开始和结束值,向量将正确填充自己。

As mentioned elsewhere, the resulting vector can be used directly with std::next_permutation.

正如别处提到的,结果向量可以直接与 std::next_permutation 一起使用。

std::next_permutation(possibilities.begin(),possibilities.end());

回答by UmmaGumma

std::vector<int> possibilities;
unsigned int i = 0;
for (i = 0; i < SIZE; i++) {
    possibilities.push_back(i);
}

Use std::vector(you need to include <vector>)

使用std::vector(你需要包括<vector>

If you want pass vector to std::next_permutationyou need to write:

如果你想将向量传递给std::next_permutation你需要写:

std::next_permutation(possibilities.begin(),possibilities.end());

also you can use vector as C style arrays. &vec[0]returns pointer to C style array.

您也可以将向量用作 C 样式数组。&vec[0]返回指向 C 风格数组的指针。

回答by xtofl

You can use the std::generate_nfunction:

您可以使用该std::generate_n功能:

std::generate_n( myarray, SIZE, increment() );

Where incrementis an object that generates numbers:

increment生成数字的对象在哪里:

struct increment {
 int value;
 int operator() () { return ++value; }
 increment():value(0){}
};

回答by Skurmedel

If you make SIZE a constant (macro or const), you can use it to specify the size of your static array. If it is not possible to use a constant, for example you are reading the intended size from outside the program, then yes you will need to allocate the memory.

如果将 SIZEconst设为常量(宏或),则可以使用它来指定静态数组的大小。如果无法使用常量,例如您正在从程序外部读取预期大小,那么是的,您将需要分配内存。

In short, if you don't know the size at compile time you probably need to allocate the memory at runtime.

简而言之,如果您在编译时不知道大小,您可能需要在运行时分配内存。

回答by claytonjwong

std::generate() can be used with a mutable lambda function to be more concise. The following C++ snippet will place the values 0..9 inclusive in a vector A of size 10 and print these values on a single line of output:

std::generate() 可以与可变的 lambda 函数一起使用以更简洁。下面的 C++ 代码片段将把值 0..9 放在大小为 10 的向量 A 中,并将这些值打印在单行输出上:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    size_t N = 10;
    vector<int> A(N);
    generate(A.begin(), A.end(), [i = 0]() mutable { return i++; });
    copy(A.begin(), A.end(), ostream_iterator<int>(cout, " "));
    cout << endl;
    return 0;
}

回答by Amir

it should be help u man

这应该是帮助你的人

int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
    a[i] = 0;    // Initialize all elements to zero.
}
. . .  // Use a as a normal array
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference

回答by bpavlov

Simply use a dynamic arrays?

简单地使用动态数组?

type * pointer;
pointer = new type[number_of_elements];

void main() 
{
int limit = 0; // Your lucky number
int * pointer = NULL; 
cout << "Please, enter limit number: ";           
cin >> n;
pointer = new int[limit+1]; // Just to be sure.
    for (int i = 0; i < n; i++) 
    {
         pointer[i] = i; // Another way is: *(pointer+i) = i (correct me if I'm wrong)   
    }
delete [] pointer; // Free some memory
pointer = NULL; // If you are "pedant"
}

I don't pretend this is the best solution. I hope it helps.

我不假装这是最好的解决方案。我希望它有帮助。