我想手动释放vector的内存。 vector 的元素是自定义类。
我用谷歌搜索了 clear 和 shrink_to_fit 就可以了。但它不适用于自定义类的 vector ,而是使用 int 的 vector 。
下面是自定义类的测试代码和定义。
using namespace std;
class HandsDisQuality{
public:
unordered_map<Hands,float,HandsHash> handsdis;
// handslist is the keys of handsdis
std::vector<Hands> handslist;
HandsDisQuality();
HandsDisQuality(std::vector<Hands>& v);
HandsDisQuality(unordered_map<Hands,float,HandsHash>& inputhandsdis);
HandsDisQuality(float range);
void init(unordered_map<Hands,float,HandsHash>& inputhandsdis);
float operator[](Hands& key);
float get(Hands& key, float defaultvalue);
float sum();
int size();
void removecard(Card& card);
void removecard(Hands & hand, vector<Card> & board);
bool normalize();
void printdata(char sep = '\t');
std::vector<Hands> * gethands();
Json::Value tojson();
void loadfromjson(Json::Value & jsonvalue);
void test();
static vector<HandsDisQuality> Generateophands(vector<float> oprange);
static vector<HandsDisQuality> Generateophands(float oprange);
};
int main() {
vector<HandsDisQuality> v(500000,HandsDisQuality(0.3));
// 14GB
cout << "init over"<<endl;
char a;
cin >> a;
v.clear();
// 14GB
cout << "after clear"<<endl;
cin >> a;
v.shrink_to_fit();
// 14GB
cout << "release memory"<<endl;
cin >> a;
}
int main() {
vector<int> v(500000000,0);
// 2.34GB
cout << "init over"<<endl;
char a;
cin >> a;
v.clear();
// 2.34GB
cout << "after clear"<<endl;
cin >> a;
v.shrink_to_fit();
// 400MB
cout << "release memory"<<endl;
cin >> a;
}
最佳答案
如果你真的想清除内存,你必须交换它:
v.swap(vector<HandsDisQuality>());
shrink_to_fit
不必收缩,它是非绑定(bind)的:
It is a non-binding request to reduce capacity() to size(). It depends on the implementation whether the request is fulfilled.
关于c++释放包含自定义类的 vector 的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54670646/