1. 程式人生 > >stl vector resize reserve

stl vector resize reserve

reserve指容量,resize會呼叫reserve,之外還會建立物件。

reserve的操作全是針對記憶體的,當capacity小於要指定的count時,reserve會reallocate建立記憶體,但是不會生成物件。

resize的操作更關心的操作物件。

打個比方:正在建造的一輛公交車,車裡面可以設定40個座椅(reserve(40);),這是它的容量,但並不是說它裡面就有了40個座椅,只能說明這部車內部空間大小可以放得下40張座椅而已。而車裡面安裝了40個座椅(resize(40);),這個時候車裡面才真正有了40個座椅,這些座椅就可以使用了。 本例轉自該連結

reserve原始碼:

void reserve(size_type _Count)
{   
    // determine new minimum length of allocated storage
    if (max_size() < _Count)
        _Xlen();    // result too long
    else if (capacity() < _Count)
    {
        // not enough room, reallocate
        pointer _Ptr = this->_Alval.allocate(_Count);


        _TRY_BEGIN
        _Umove(this->_Myfirst, this->_Mylast, _Ptr);
        _CATCH_ALL
        this->_Alval.deallocate(_Ptr, _Count);
        _RERAISE;
        _CATCH_END


        size_type _Size = size();
        if (this->_Myfirst != 0)
            {    // destroy and deallocate old array
            _Destroy(this->_Myfirst, this->_Mylast);
            this->_Alval.deallocate(this->_Myfirst,
                this->_Myend - this->_Myfirst);
            }


        this->_Orphan_all();
        this->_Myend = _Ptr + _Count;
        this->_Mylast = _Ptr + _Size;
        this->_Myfirst = _Ptr;
    }
}
resize原始碼:
void resize(size_type _Newsize)
{    
    // determine new length, padding with _Ty() elements as needed
    if (_Newsize < size())
        erase(begin() + _Newsize, end());
    else if (size() < _Newsize)
    {    
        // pad as needed
        _Reserve(_Newsize - size());
        _Uninitialized_default_fill_n(this->_Mylast, _Newsize - size(),
            (_Ty *)0, this->_Alval);
        this->_Mylast += _Newsize - size();
    }
}


void resize(size_type _Newsize, _Ty _Val)
{   
    // determine new length, padding with _Val elements as needed
    if (size() < _Newsize)
        _Insert_n(end(), _Newsize - size(), _Val);
    else if (_Newsize < size())
        erase(begin() + _Newsize, end());
}