简体   繁体   English

释放分配给二维向量的内存

[英]Freeing memory allocated to a 2-dimensional vector

I have the following 2 dimension vector: 我有以下2维向量:

std::vector<std::vector<int>> m_scoreVector; 

I try the following code to free the allocated memory. 我尝试以下代码释放分配的内存。 But, it does not work. 但是,它不起作用。 Just a small portion of memory will be releases: 只有一小部分内存会释放:

for (int k = 0; k < m_scoreVector.size(); ++k){     
    std::vector<int>().swap(m_scoreVector[k]);
    m_scoreVector[k].shrink_to_fit();   
    m_scoreVector[k].clear();
}

std::vector<std::vector<int>>().swap(m_scoreVector);
m_scoreVector.shrink_to_fit();
m_scoreVector.clear();

I am new to memory management. 我是内存管理的新手。 Please let me know how should I free the allocated memory for this vector. 请让我知道如何释放该向量的分配内存。 Thanks. 谢谢。

Vectors manage the memory for you. 向量为您管理内存。 They will free the memory when they go out of scope. 当超出范围时,它们将释放内存。 In general, if you don't allocate memory with new or malloc, you don't need to worry about freeing it either. 通常,如果您不使用new或malloc分配内存,则无需担心释放内存。

swap() and shrink_to_fit() are two ways to free vector memory,you can not use it together swap()和rinkle_to_fit()是释放向量内存的两种方法,不能一起使用

try this code: 试试这个代码:

for (int k = 0; k < m_scoreVector.size(); ++k){     
    m_scoreVector[k].clear();
    m_scoreVector[k].shrink_to_fit();   
}
m_scoreVector.clear();
m_scoreVector.shrink_to_fit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM