提升 性能的幾種方法:
- 提前分配空間
- 向 插入元素時使用 而非
- 在填充或者拷貝 的時候,使用賦值,而非 或者
- 或者 並不會釋放 佔用的內存空間,可以使用 或者 來釋放。其實有一個成員函數 是用來釋放內存空間的,但是有些編譯器不支持(聽說),反正 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爲例)
關於 是可以在 找到容器中 中第 的數(其中第0小是容器中最小的數),並將這個數放在 的位置上。保證了 前都是小於該數的數,之後都是大於該數的數。
如果加上比較函數,那麼可以變爲找容器中第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
*/