首页 > 编程语言 >Delete vector contents and free up memory in C++

Delete vector contents and free up memory in C++

时间:2023-06-22 15:15:04浏览次数:48  
标签:std function capacity up free vector memory include

 

Delete vector contents and free up memory in C++

Google Translate Icon

This post will discuss how to delete the vector’s contents and free up the memory allocated by the vector to store objects in C++.

1. Using vector::clear function

We can use the vector::clear function to remove all elements from the vector. It works by calling a destructor on each vector object, but the underlying storage is not released. So, we’re left with a vector of size 0 but some finite capacity.

 

 
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream> #include <vector>   int main() {     std::vector<int> v = { 1, 2, 3, 4, 5 };       v.clear();     std::cout << "The vector size is " << v.size() << ", and its "               << "capacity is " << v.capacity();       return 0; }

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 5

 
Starting with C++11, we can call the vector::shrink_to_fit function after clear(), which reduces the vector’s capacity to fir the size. It works by “requesting” a reallocation on the vector.

 

 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> #include <vector>   int main() {     std::vector<int> v = { 1, 2, 3, 4, 5 };       v.clear();     v.shrink_to_fit();       std::cout << "The vector size is " << v.size() << ", and its "               << "capacity is " << v.capacity();       return 0; }

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

2. Using vector::erase function

Another solution is to call the vector::erase function on the vector, as shown below. This also suffers from the same problem as the clear() function, i.e., reallocation of memory is not guaranteed to happen on the vector.

 

 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> #include <vector>   int main() {     std::vector<int> v = { 1, 2, 3, 4, 5 };       v.erase(v.begin(), v.end());     v.shrink_to_fit();       std::cout << "The vector size is " << v.size() << ", and its "               << "capacity is " << v.capacity();       return 0; }

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

3. Using vector::resize function

We can also use the vector::resize function for resizing the vector. Notice that this function does not destroy the vector objects, and all references to objects remain valid.

 

 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> #include <vector>   int main() {     std::vector<int> v = { 1, 2, 3, 4, 5 };       v.resize(0);     v.shrink_to_fit();       std::cout << "The vector size is " << v.size() << ", and its "               << "capacity is " << v.capacity();       return 0; }

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

4. Using vector::swap function

All the above solutions fail to release the memory allocated to the vector object without calling the vector::shrink_to_fit function. The shrink_to_fit() shrinks the capacity to fit the size, but we can’t entirely rely on it. This is because it makes a non-binding request, and the vector implementation is free to ignore it completely.

There is another workaround to free the memory taken by the vector object. The idea is to swap the vector with an empty vector (with no memory allocated). This will de-allocate the memory taken by the vector and is always guaranteed to work.

 

 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> #include <vector>   int main() {     std::vector<int> v = { 1, 2, 3, 4, 5 };       std::vector<int>().swap(v);     std::cout << "The vector size is " << v.size() << ", and its "               << "capacity is " << v.capacity();       return 0; }  

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

That’s all about deleting vector contents and free up memory in C++.

<iframe data-google-container-id="4" data-load-complete="true" frameborder="0" height="1" id="google_ads_iframe_/22771334302/TechieDelight_S2S_Leaderboard_ROS_BTF_0" marginheight="0" marginwidth="0" name="google_ads_iframe_/22771334302/TechieDelight_S2S_Leaderboard_ROS_BTF_0" scrolling="no" title="3rd party ad content" width="1"></iframe>
Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)     Techie DelightLogo   Resources Online IDE Company Techie Delight © 2023 All Rights Reserved.    
#include <iostream>
#include <vector>
class TestClass
{
    public:
    TestClass()
    {
    }
    ~TestClass()
    {
        std::cout << "\r\nTestClass destroy \r\n";
    }
};
int main()
{
    TestClass a;TestClass b; TestClass c; TestClass d; TestClass e;
    std::vector<TestClass> v = { a,b,c,d,e };
    std::vector<TestClass>().swap(v);
    std::cout << "The vector size is " << v.size() << ", and its "
              << "capacity is " << v.capacity();
    return 0;
}

output:
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
The vector size is 0, and its capacity is 0
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 
TestClass destroy 

 

标签:std,function,capacity,up,free,vector,memory,include
From: https://www.cnblogs.com/ioriwellings/p/17497746.html

相关文章

  • 二分查找法lowerCeil版(找某个重复值的最小下标)利用二分upper法实现
    也是利用二分的upper法实现的,不知道什么是upper?看这里->二分查找法upper版(找大于某个值的最小下标)递归+非递归版-翰林猿-博客园(cnblogs.com)思路:先利用upper找到上界的index拿着index-1的下标(也就是重复值的最大下标)向前遍历,一直到遍历到发现不相等的元素即可。......
  • 【点云配准】super4PCS
    在OpenGR的目录下,输入time-p./build/apps/Super4PCS/Super4PCS-i./assets/hippo1.ply./assets/hippo2.ply-o0.7-d0.01-t1000-n400-rsuper4pcs.objtime-p为控制台命令,作用为统计程序运行耗费的时间Super4PCS为应用程序的名称,-i命令表示后面为输入的数据名(带路径......
  • 二分查找法ceil版(找某个重复值的最大下标)利用二分upper法实现
    如果有等于target的元素就返回最大的下标元素。如果没有等于target的元素,那么就返回大于target的最小元素,即这一篇文章实现的upper函数。二分查找法upper版(找大于某个值的最小下标)递归+非递归版-翰林猿-博客园(cnblogs.com),当然你们也可以更改返回值-1什么的作为查找......
  • 二分查找法upper版(找大于某个值的最小下标)递归+非递归版
    需求:比如说查询一个班级大于60分的最低分等等。思路与二分法基本相同,只不过是对比的逻辑发生了一些小变化,这里所说的上界就是指大于某个值的最小下标。当mid<target:说明target的上界还在mid的右边,所以要去找比mid大的当mid>target:说明mid有可能是target的上界,所以......
  • POSTGRESQL 15 pg_basebackup 新功能,LOCAL backup 与 数据强力压缩
    与MYSQL不一样,开源XTRABACKUP的备份软件无法跟上MYSQL版本的更迭,PG这点做的是一贯的好。从来没有让人失望过。所以POSTGRESQL数据的备份一直就不是一个问题,众多的工具以及pg_basebackup良好的功能,让POSTGRESQL备份起来速度与硬件有关。但基于POSTGRESQL本身的原理,数据库表......
  • POSTGRESQL vacuum_freeze系列中 三个参数与 vacuum的关系
    开头还是介绍一下群,如果感兴趣polardb,mongodb,mysql,postgresql ,redis等有问题,有需求都可以加群群内有各大数据库行业大咖,CTO,可以解决你的问题。最近在整理VACUUM相关知识的时候,发现一个问题对于vacuum_freeze的3个参数的概念掌握的不牢固,那么只能进行恶补了。本次的三个......
  • Apache Drupal URL重写
    在drupal跟目录下有个.htaccess文件,这个文件中就有URL地址重写的配置信息,配置信息如下:#Variousrewriterules.<IfModulemod_rewrite.c>RewriteEngineon#Ifyoursitecanbeaccessedbothwithandwithoutthe'www.'prefix,you#canuseoneofthefoll......
  • Ubuntu 下Drupal的安装
    一些有用的安装命令:sudonautilus指用跟用户权限打开文件浏览器,这样你可以对所有文件进行读写和修改权限的操作。sudo/etc/init.d/apache2restart重启apache详细的安装步骤可以在下面地址看到:http://drupalchina.org/node/5249如何使用汉化包参看下面地址:http://drupalchina.org......
  • 手撕Vector底层源码
    publicabstractclassAbstractList<E>extendsAbstractCollection<E>implementsList<E>{//外部操作数protectedtransientintmodCount=0;}publicclassVector<E>extendsAbstractList<E>implementsList<E>{//元素......
  • B/S WebUploader 分块上传
    ​ java两台服务器之间,大文件上传(续传),采用了Socket通信机制以及JavaIO流两个技术点,具体思路如下: 实现思路:1、服:利用ServerSocket搭建服务器,开启相应端口,进行长连接操作2、服:使用ServerSocket.accept()方法进行阻塞,接收客户端请求3、服:每接收到一个Socket就建立一个新的线......