1. 程式人生 > >c++ 重設容器的長度(resize)

c++ 重設容器的長度(resize)

 

#include <iostream>
#include <vector>
using namespace std;
int main ()
{
    vector<int> myvector;
    
    // set some initial content:
    for (int i=1;i<10;i++) myvector.push_back(i);//長度為9
    
    myvector.resize(5);//重新設定長度為5,多餘的元素刪掉
    myvector.resize(8,100);//重新設定長度為8,填充元素為100
myvector.resize(12);//預設填充的元素是0 cout << "myvector contains:"; for (int i=0;i<myvector.size();i++) cout << ' ' << myvector[i]; cout << '\n'; return 0; }

輸出

myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0