我正在尝试使用C ++中的initialize_list
在构造函数中初始化动态数组。我该如何实现?
#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <utility>
using namespace std;
class vec {
private:
// Variable to store the number of elements contained in this vec.
size_t elements;
// Pointer to store the address of the dynamically allocated memory.
double *data;
public:
/*
* Constructor to create a vec variable with the contents of 'ilist'.
*/
vec(initializer_list<double> ilist);
}
int main() {
vec x = { 1, 2, 3 }; // should call to the constructor
return 0;
}
最佳答案
initializer_list
具有size
方法,它为您提供信息new
必须分配多少个元素,因此可能是:
vec(initializer_list<double> ilist)
{
elements = ilist.size();
data = new double[ ilist.size() ];
std::copy(ilist.begin(),ilist.end(),data);
}
关于c++ - 如何使用initializer_ist在构造函数中初始化动态数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56355230/