如何解决如何实现插入向量c ++?
我必须使用operator[]
,5,push_back
和insert
的规则来实现向量类。
template<class T>
class MyVector
{
private:
int size_;
int capacity_;
T* data;
public:
typedef T* it;
it begin();
it end();
void push_back(const T& value);
我开始创建构造函数,复制构造函数,移动构造函数,复制赋值运算符,移动赋值运算符。
我这样实现了begin()
和end()
:
template<class T>
typename MyVector<T>::it MyVector<T>::begin()
{
return data;
}
template<class T>
typename MyVector<T>::it MyVector<T>::end()
{
return data + size();
}
我不知道如何实现push_back()
和insert()
。
对于push_back()
,我想到了这样的事情:
void push_back(const T & v)
{
if (size_ < capacity_)
data [size_++] = v;
}
但是对于insert()
,我不知道。
您能帮我实现insert()
吗?
解决方法
您的push_back()
执行不正确。当size_
等于capacity_
时,它需要增大数组,以便为要推送的新值腾出空间。
同样,如果需要,您的insert()
也需要增加数组。然后,它可以找出新值应该到达的索引,将所有该索引元素之后向上移动数组中的一个插槽,然后将新值分配给该索引处的元素。 / p>
尝试这样的事情:
template<class T>
void MyVector<T>::grow()
{
static const int delta = ...; // <-- use whatever value makes sense for your use case...
int new_cap = capacity_ + delta;
T* new_data = new T[new_cap];
for(int i = 0; i < size_; ++i) {
new_data[i] = std::move(data[i]);
}
delete[] data;
data = new_data;
capacity_ = new_cap;
}
template<class T>
void MyVector<T>::push_back(const T & v)
{
if (size_ == capacity_)
grow();
data[size_] = v;
++size_;
}
template<class T>
void MyVector<T>::insert(typename MyVector<T>::it pos,const T & v)
{
int index = pos - data;
if (index < 0 || index > size_)
return; // or throw...
if (size_ == capacity_)
grow();
for(int i = size_ - 1; i >= index; --i)
data[i+1] = data[i];
data[index] = v;
++size_;
}
,
要插入,必须。
- 为多余的数据腾出空间。 (因为您还需要在push_back / emplace_back中这样做)。
- 将当前数据从插入点移动到新的偏移量。
- 将插入的数据复制到其中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。