提升vector性能的幾種方法 & 線性求容器中第k小

提升 vectorvector 性能的幾種方法:

  1. 提前分配空間
  2. vectorvector 插入元素時使用 emplace_back()emplace\_back() 而非 push_back()push\_back()
  3. 在填充或者拷貝 vectorvector 的時候,使用賦值,而非 insert()insert() 或者 push_back()push\_back()
  4. clear()clear() 或者 erase()erase() 並不會釋放 vectorvector 佔用的內存空間,可以使用 vector<int>(vt).swap(vt)vector<int>(vt).swap(vt) 或者 vector<int>().swap(vt)vector<int>().swap(vt) 來釋放。其實有一個成員函數 shrink_to_fit()shrink\_to\_fit() 是用來釋放內存空間的,但是有些編譯器不支持(聽說),反正 CLion 和 VS 我都試過了,不能釋放。

釋放原理:

vector()使用vector的默認構造函數建立臨時vector對象,再在該臨時對象上調用swap成員
swap調用之後對象vt佔用的空間就等於一個默認構造的對象的大小
臨時對象就具有原來對象v的大小,而該臨時對象隨即就會被析構,從而其佔用的空間也被釋放。

驗證代碼:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;

int read()
{
    int x = 0, f = 1; char c = getchar();
    while (c < '0' || c > '9') { if (c == '-') f = -f; c = getchar(); }
    while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}

const int maxN = 50004;

int main()
{
    int n; n = read();
    vector<int>vt(100);
    for(int i = 0; i < n; ++ i )
        vt[i] = read();

    vt.shrink_to_fit();
    cout << vt.capacity() << endl;

    vt.clear();
    cout << vt.capacity() << endl;

    vector<int>(vt).swap(vt);
//    vector<int>().swap(vt);
    cout << vt.capacity() << endl;
    return 0;
}
/*
10
10 9 8 7 6 5 4 3 2 1
 */

在這裏插入圖片描述

學習博客:
提升vector性能的幾個技巧
簡單的程序詮釋C++ STL算法系列之十五:swap

線性求容器中第k小(vector爲例)

關於 nth_element(first,nth,last)nth\_element(first,nth,last) 是可以在 O(n)O(n) 找到容器中 [first,last)[first,last) 中第 nthnth 的數(其中第0小是容器中最小的數),並將這個數放在 nthnth 的位置上。保證了 nthnth 前都是小於該數的數,之後都是大於該數的數。

如果加上比較函數,那麼可以變爲找容器中第k大

代碼:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int read()
{
    int x = 0, f = 1; char c = getchar();
    while (c < '0' || c > '9') { if (c == '-') f = -f; c = getchar(); }
    while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}

const int maxN = 50004;

int main()
{
    int n; n = read();
    vector<int>vt(100);
    for(int i = 0; i < n; ++ i )
        vt[i] = read();
    int pos = read();
    nth_element(vt.begin(), vt.begin() + pos, vt.begin() + n);
    for(int i = 0; i < n; ++ i)
        cout << vt[i] << ' ';
    cout << endl;
    nth_element(vt.begin(), vt.begin() + pos, vt.begin() + n, greater<int>());
    for(int i = 0; i < n; ++ i)
        cout << vt[i] << ' ';
    cout << endl;
    return 0;
}
/*
10
10 9 8 7 6 5 4 3 2 1
2
 */

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章