栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

stl vector使用之resize和reserve的区别

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

stl vector使用之resize和reserve的区别

void resize (size_type n);

void resize (size_type n, const value_type& val);

调整容器大小,使其包含n个元素。

1,如果n小于等于当前容器大小,则容器缩小为前n个元素,删除后面的元素。

#include 
#include 
#include 

int main()
{
    std::vector test;
    test.push_back(1);
    test.push_back(11);
    test.push_back(12);
    test.push_back(13);

    test.resize(2); //容器大小没变,元素减少了
    
    printf("test.capacity = %lu, size = %lun", test.capacity(), test.size()); //capacity = 4, size = 0
    for(unsigned int i = 0; i < test.size(); i++)
    {
        printf("%dn", test.at(i));
    }
    return 0;
}

 2,如果n大于当前容器大小(会引起内存重新分配),则容器扩展内容,在容器的末尾插入足够多的元素以达到n的大小。如果指定了val,则将新元素初始化为val的副本,否则,则对新元素进行值初始化。

#include 
#include 
#include 

int main()
{
    std::vector test;
    test.push_back(1);
    test.push_back(11);
    test.push_back(12);
    test.push_back(13);

    test.resize(6); //容器大小改变
    
    printf("test.capacity = %lu, size = %lun", test.capacity(), test.size()); //capacity = 4, size = 0
    for(unsigned int i = 0; i < test.size(); i++)
    {
        printf("%dn", test.at(i));
    }
    return 0;
}

void reserve (size_type n);

调用容器大小,至少足够容纳n个元素。

如果n大于当前vector容器的容量,该函数将导致容器重新分配存储空间,将容量增加到n(或更大)。在所有其他情况下,函数调用不会导致重新分配,vector容量也不会受到影响。

 

#include 
#include 
#include 

int main()
{
    std::vector test;
    test.push_back(1);
    test.push_back(11);
    test.push_back(12);
    test.push_back(13);

    test.reserve(2); //
    
    printf("test.capacity = %lu, size = %lun", test.capacity(), test.size()); //capacity = 4, size = 0
    for(unsigned int i = 0; i < test.size(); i++)
    {
        printf("%dn", test.at(i));
    }
    return 0;
}

#include 
#include 
#include 

int main()
{
    std::vector test;
    test.push_back(1);
    test.push_back(11);
    test.push_back(12);
    test.push_back(13);

    test.reserve(12); //
    
    printf("test.capacity = %lu, size = %lun", test.capacity(), test.size()); //capacity = 4, size = 0
    for(unsigned int i = 0; i < test.size(); i++)
    {
        printf("%dn", test.at(i));
    }
    return 0;
}

 

 容量扩大,元素不变。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641770.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号