[英]How to initialize dynamic array in constructor using initializer_ist?
I am trying to initialize the dynamic array in the constructor using initialize_list
in C++. 我正在尝试使用C ++中的
initialize_list
构造函数中的动态数组。 How can I achieve this? 我该如何实现?
#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;
}
Use a standard std::vector
container instead of a raw pointer. 使用标准的
std::vector
容器而不是原始指针。 std::vector
is a wrapper for a dynamic array, and it has a constructor that accepts a std::initializer_list
as input. std::vector
是动态数组的包装器,它具有一个接受std::initializer_list
作为输入的构造std::initializer_list
。
#include <initializer_list>
#include <iostream>
#include <vector>
using namespace std;
class vec {
private:
vector<double> data;
public:
vec(initializer_list<double> ilist) : data(ilist) {}
};
initializer_list
has size
method, it gives you information how many elements must be allocated by new
, so it could be: initializer_list
具有size
方法,它为您提供信息new
必须分配多少个元素,因此可能是:
vec(initializer_list<double> ilist)
{
elements = ilist.size();
data = new double[ ilist.size() ];
std::copy(ilist.begin(),ilist.end(),data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.