vector::shrink_to_fit()

liji_digital發表於2019-09-01

如圖示(圖片來自侯捷的<<STL原始碼剖析>>),vector::capacity()代表了vector從begin()開始的連續空間的記憶體量。 

vector::erase(begin() + n)函式可以刪去vector中第n位置的元素。但是刪除之後,vector佔用的capacity不一定減少。C++11增加了shrink_to_fit函式,可以在執行erase之後讓vector的size()等於capacity()。

看下面例子。構造一個vector {1,2,3,4},然後點選deduct按鈕,刪去第3個元素。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <vector>


using namespace std;

vector<int> vec;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{

    QString qstrInput = ui->lineEdit->text();
    QStringList qstrlst = qstrInput.split(QString(","));
    foreach(QString qstrItem, qstrlst)
    {
        int iVal = qstrItem.toInt();
        vec.push_back(iVal);
    }

    vec.shrink_to_fit();

    ui->lineEdit_3->setText(QString().setNum(vec.size()));
    ui->lineEdit_4->setText(QString().setNum(vec.capacity()));

    ui->label->setText(QString().setNum(*prev(vec.end())));
}

void MainWindow::on_pushButton_2_clicked()
{
    int iOldSize = vec.size();
    int iIndex = ui->lineEdit_2->text().toInt();
    vec.erase(vec.begin() + iIndex);
    //vec.shrink_to_fit();
    int iTail = *prev(vec.end());
    ui->label->setText(QString().setNum(iTail));
    ui->lineEdit_3->setText(QString().setNum(vec.size()));
    ui->lineEdit_4->setText(QString().setNum(vec.capacity()));
}

效果:capacity 仍然等於4

加入shrink_to_fit函式,capacity 變為3

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <vector>


using namespace std;

vector<int> vec;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{

    QString qstrInput = ui->lineEdit->text();
    QStringList qstrlst = qstrInput.split(QString(","));
    foreach(QString qstrItem, qstrlst)
    {
        int iVal = qstrItem.toInt();
        vec.push_back(iVal);
    }

    vec.shrink_to_fit();

    ui->lineEdit_3->setText(QString().setNum(vec.size()));
    ui->lineEdit_4->setText(QString().setNum(vec.capacity()));

    ui->label->setText(QString().setNum(*prev(vec.end())));
}

void MainWindow::on_pushButton_2_clicked()
{
    int iOldSize = vec.size();
    int iIndex = ui->lineEdit_2->text().toInt();
    vec.erase(vec.begin() + iIndex);
    vec.shrink_to_fit();
    int iTail = *prev(vec.end());
    ui->label->setText(QString().setNum(iTail));
    ui->lineEdit_3->setText(QString().setNum(vec.size()));
    ui->lineEdit_4->setText(QString().setNum(vec.capacity()));
}