[英]c++ how to initialize const elements of an array
i need a way to initialize const elements of an array for the program i am currently working on. 我需要一种方法来初始化我目前正在处理的程序的数组的const元素。 The problem is that i have to initialize these elements with a function, there is no way to do it like this:
问题是我必须用函数初始化这些元素,没有办法像这样做:
const int array[255] = {1, 1278632, 188, ...};
because its alot of data i have to generate. 因为我必须生成很多数据。 What i tried is to memcpy data to the const int's but that can't work and hasn't worked.
我尝试的是将数据memcpy到const int,但这不起作用,但没有奏效。
const int array[255];
void generateData(){
for(int i = 0; i < 255; i++) {
initializeSomehowTo(5, array[i]);
}
}
I hope you understand what i am trying, sorry if i doubled the question, i must have overlooked it. 我希望你明白我在想什么,对不起,如果我把问题翻倍,我一定忽略了它。
How about this? 这个怎么样?
#include <array>
typedef std::array<int, 255> Array;
const Array array = generateData();
Array generateData(){
Array a;
for(int i = 0; i < a.size(); i++) {
initializeSomehowTo(a[i]);
}
return a;
}
The easiest approach is to get the filled array from a function and use that to initialize your const
(or constexpr
) object. 最简单的方法是从函数中获取填充数组,并使用它来初始化
const
(或constexpr
)对象。 However, built-in arrays can't be copied but std::array<T, N>
be: 但是,无法复制内置数组,但
std::array<T, N>
为:
std::array<T, 255> array = initializeData();
If you need a built-in array, I can imagine initializing a static
member of a class (template, actually) where the index is expanded from indices expanded from an std::make_index_sequence<255>
and used as positional argument in the array, ie, something along these lines: 如果你需要一个内置数组,我可以想象初始化一个类的
static
成员(实际上是模板),其中索引从std::make_index_sequence<255>
扩展的索引扩展并用作数组中的位置参数,即,沿着这些方向的东西:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>
int some_function(std::size_t i) { return i; }
template <typename> struct initialized_array_base;
template <std::size_t... I>
struct initialized_array_base<std::index_sequence<I...>> {
static const int array[sizeof...(I)];
};
template <std::size_t... I>
int const initialized_array_base<std::index_sequence<I...>>::array[sizeof...(I)]
= { some_function(I)... };
struct initialized_array
:initialized_array_base<std::make_index_sequence<256>> {
};
int main() {
std::copy(std::begin(initialized_array::array),
std::end(initialized_array::array),
std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
}
You can create a writable array, initialize it, and, then, create a const reference to it. 您可以创建一个可写数组,对其进行初始化,然后创建一个const引用。
int arry[255];
void generateData(){
for(int i = 0; i < 255; i++) {
initializeSomehowTo(5, arry[i]);
}
}
const int (&array)[255] = arry;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.