有关vector使用clear()的补充

有关vector使用clear()的补充

众所周知,\(map,set\)这2个\(clear()\)莫有问题,可\(vector\)就不一样,看下面

#include<bits/stdc++.h>
using namespace std;
vector<int>g;
int main()
{
    g.push_back(4);
    g.push_back(8);
    g.clear();
    for(auto v:g) printf("%d ",v);printf("\n");
    printf("g[0]:%d\n",g[0]);
    printf("g.size():%d\n",g.size());
    printf("Over 1\n");

    g.push_back(333);
    g.push_back(444);
    for(auto v:g) printf("%d ",v);printf("\n");
    printf("g[0]:%d\n",g[0]);
    printf("g.size():%d\n",g.size());
    printf("Over 2\n");
    // 结论:合理运用g.size()即可使其正常清空
    return 0; 
}
g[0]:4    
g.size():0
Over 1    
333 444   
g[0]:333  
g.size():2
Over 2   
posted @ 2024-11-05 21:12  左边之上  阅读(14)  评论(0)    收藏  举报