提升 v e c t o r vector vector 性能的几种方法:
- 提前分配空间
- 向 v e c t o r vector vector 插入元素时使用 e m p l a c e _ b a c k ( ) emplace\_back() emplace_back() 而非 p u s h _ b a c k ( ) push\_back() push_back()
- 在填充或者拷贝 v e c t o r vector vector 的时候,使用赋值,而非 i n s e r t ( ) insert() insert() 或者 p u s h _ b a c k ( ) push\_back() push_back()
- c l e a r ( ) clear() clear() 或者 e r a s e ( ) erase() erase() 并不会释放 v e c t o r vector vector 占用的内存空间,可以使用 v e c t o r < i n t > ( v t ) . s w a p ( v t ) vector<int>(vt).swap(vt) vector<int>(vt).swap(vt) 或者 v e c t o r < i n t > ( ) . s w a p ( v t ) vector<int>().swap(vt) vector<int>().swap(vt) 来释放。其实有一个成员函数 s h r i n k _ t o _ f i t ( ) 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为例)
关于 n t h _ e l e m e n t ( f i r s t , n t h , l a s t ) nth\_element(first,nth,last) nth_element(first,nth,last) 是可以在 O ( n ) O(n) O(n) 找到容器中 [ f i r s t , l a s t ) [first,last) [first,last) 中第 n t h nth nth 的数(其中第0小是容器中最小的数),并将这个数放在 n t h nth nth 的位置上。保证了 n t h nth nth 前都是小于该数的数,之后都是大于该数的数。
如果加上比较函数,那么可以变为找容器中第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
*/