我想手动释放vector的内存。向量的元素是自定义类。
我在Google上搜索了clear和rinkle_to_fit将完成此工作。但是它不适用于自定义类的向量,也不适用于int的向量。
下面是自定义类的测试代码和定义。
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;
}
答案 0 :(得分:2)
如果您确实想清除内存,则必须交换它:
v.swap(vector<HandsDisQuality>());
shrink_to_fit
不必缩小,它没有约束力:
将Capacity()减小为size()是非绑定请求。是否满足请求取决于实现。