Question in C ++

I want to initialize a double array of size 200, and its value is from 0 to 199 from the index from 0 to 199 in C ++. I know I can make this a simple For loop, but is there a way to initialize a double array like this?

thank

+3
source share
8 answers

Not really. The for loop is your best option:

double array[200];
for(int i = 0; i < 200; i++)
    array[i] = static_cast<double>(i);
+10
source

Here is the path with std::generate:

template <typename T>
class nexter
{
public:
    nexter(T start = T())
        : value_(start)
    {
    }

    T operator()()
    {
        return value_++;
    }

private:
    T value_;
};

int main()
{
    double data[200];
    std::generate(data, data + 200, nexter<double>());
}

And if you use C ++ 0x, you can skip the functor:

int main()
{
    double data[200];
    double next = 0.0;
    std::generate(data, data + 200, [&next]() { return next++; } );
}
+7
source

counting_iterator:

const int SIZE = 200;
double array[SIZE];
std::copy(counting_iterator<int>(0), counting_iterator<int>(SIZE), array);
+7

, anthony-arnold, ++ ( deque):

std::vector<double> array ;
array.reserve(200) ; // only for vectors, if you want
                     // to avoid reallocations

for(int i = 0; i < 200; i++)
    array.push_back(i) ;
+2

, . , , .

double array[200];

for(int i=0 ; i<200 ; i++) { 
    array[i] = (double)i; 
}
+1

( , ;

double arr[5] = {0, 1, 2}; // arr = [0.0 ,1.0 ,2.0 ,0.0 ,0.0]

, .

, :

double arr[] = {0, 1, 2, 3, /* ... */, 199}; 

.

0

200 , .

C . Think Boost for . , .

200 /, .

++ template, . template . , .

0

I think for-loop is the easiest and most suitable solution for your business. If you just want to find out another way to do this, you can use std::transform:

#include <vector>
#include <algorithm>

double op_increase (double i) { return static_cast<double>(static_cast<int>(i)+1); }

int main() 
{ 
    std::vector<double> x( 200 ); // all elements were initialized to 0.0 here
    std::transform( x.begin(), x.end()-1, x.begin()+1, op_increase );

    return 0; 
} 
0
source

Source: https://habr.com/ru/post/1754548/


All Articles