vector c++构造函数怎么写
1个回答
展开全部
构造函数有多个
explicit Vector(int initsize = 0); //explicit是为了防止让一个实参的构造函数发生隐式转换
Vector(int initsize, T value);
Vector(iterator b, iterator e); //接受两个迭代器创建拷贝的构造函数 ,这里的迭代器的创建是指针,见上面
Vector(std::initializer_list<T> l);
Vector(const Vector &rhs);
template <typename T>
Vector<T>::Vector(int initsize = 0) :thesize(initsize), thecapacity(initsize + SPARE_CAPACITY)
{
elem = new T[thecapacity];
assert(elem != NULL); //存储分配失败则退出;
}
template<typename T>
Vector<T>::Vector(std::initializer_list<T> l) //列表初始化,新标准
{
thesize = l.size();
thecapacity = thesize + SPARE_CAPACITY;
elem = new T[thecapacity];
assert(elem != NULL);
int i = 0;
auto beg = l.begin();
while (beg != l.end() && i != thesize)
{
elem[i] = *beg;
++i;
++beg;
}
}
template <typename T>
Vector<T>::Vector(int initsize, T value) :thesize(initsize), thecapacity(initsize + SPARE_CAPACITY)
{
elem = new T[thecapacity];
assert(elem != NULL); //存储分配失败则退出;
for (int i = 0; i != thesize; ++i)
elem[i] = value;
}
template <typename T>
Vector<T>::Vector(iterator b, iterator e)
{
thesize = e - b;
thecapacity = thesize + SPARE_CAPACITY;
elem = new T[thecapacity];
assert(elem != NULL);
for (int i = 0; b != e&&i != thesize; ++i)
{
elem[i] = *b;
++b;
}
}
//拷贝构造函数,接受一个容器为另一个容器的拷贝(深拷贝)
template <typename T>
Vector<T>::Vector(const Vector &rhs)
{
thesize = rhs.thesize;
thecapacity = rhs.thecapacity;
elem = new T[thecapacity];
assert(elem != NULL);
for (int i = 0; i != thesize; ++i)
elem[i] = rhs.elem[i];
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询