c++释放包含自定义类的 vector 的内存

标签 c++ stdvector

我想手动释放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>());

shr​​ink_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/

相关文章:

c++ - 派生类的模板特化

c++ - C硬编码typedef结构数组

c++ - 替换一堆 std::vector 条目

c++ - 为什么删除 End-Iterator 不会导致 Segmentation Fault with shared_ptr?

c++ - 序列化一个浮点 vector

c++ - 如何检查科学记数法是否为 double C++

c++ - 何时在 C++ 对中使用点和箭头运算符?

c# - 将 float[][] 编码为 float**

c++ - 将空 vector 传递给对象的 "correct"方法是什么?

c++ - 这两个功能没有合并为一个功能是有原因的吗?