其他分享
首页 > 其他分享> > std::vector中assign resize reserve的区别

std::vector中assign resize reserve的区别

作者:互联网

1.assign 用于初始化

 

2.resize 改变capacity,与size

 

3.reserve 改变capacity,不改变size

   超过size的capacity不可直接访问,可通过push_back追加,若size < capacity, push_back操作不尽心内存分配。

测试代码:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>

void ShowInfo(const std::string& info, const std::vector<char>& vec)
{
    std::cout << info << ":" 
        << "capacity=" << vec.capacity() 
        << ", " 
        << "size=" << vec.size() 
        << std::endl;
}

int main()
{
    std::vector<char> vecTest;
    
    vecTest.assign(5, 0);
    ShowInfo("assign", vecTest);

    vecTest.resize(10);
    ShowInfo("resize", vecTest);

    vecTest.reserve(15);
    ShowInfo("reserve", vecTest);

    vecTest.resize(10);
    ShowInfo("resize to 10", vecTest);

    system("pause");

    return 0;
}

结果:

assign:capacity=5, size=5
resize:capacity=10, size=10
reserve:capacity=15, size=10
resize to 10:capacity=15, size=10

 

标签:std,vecTest,ShowInfo,capacity,10,vector,assign,resize,size
来源: https://blog.51cto.com/u_4135183/2822759