我正在尝试使用 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/