# 陣列型式（Array idiom） vector

#include <vector>

vector<int> ivector(10);

``#include <iostream> #include <vector>using namespace std; int main() {     vector<int> ivector(10);     for(int i = 0; i < ivector.size(); i++) {        ivector[i] = i;    }     for(int i = 0; i < ivector.size(); i++) {        cout << ivector[i] << " ";    }    cout << endl;    return 0; }``

0 1 2 3 4 5 6 7 8 9

vector<int> ivector(10, 5);

``#include <iostream> #include <vector>using namespace std; int main() {     int iarr[] = {1, 2, 3, 4, 5};     vector<int> ivector(iarr, iarr + 5);     for(int i = 0; i < ivector.size(); i++) {        cout << ivector[i] << " ";    }    cout << endl;     return 0; }``

1 2 3 4 5

``#include <iostream> #include <vector>using namespace std; int main() {     int iarr[] = {1, 2, 3, 4, 5};     vector<int> ivector(iarr + 1, iarr + 4);     for(int i = 0; i < ivector.size(); i++) {        cout << ivector[i] << " ";    }    cout << endl;    return 0; }``

2 3 4

vector可以使用另一個vector作為引數來建構，例如以ivector1作為引數來建構ivector2：
vector<int> ivector1(5, 1);
vector<int> ivector2(ivector1);

vector可以使用=直接指定給另一個vector，這會將vector的值複製給被指定的vector，例如：

``#include <iostream> #include <vector>using namespace std; int main() {     vector<int> ivector1(5, 1);    vector<int> ivector2; // 定義一個空的vector     ivector2 = ivector1;     for(int i = 0; i < ivector2.size(); i++) {        cout << ivector2[i] << " ";    }    cout << endl;     ivector2[0] = 2;    for(int i = 0; i < ivector2.size(); i++) {        cout << ivector2[i] << " ";    }    cout << endl;     for(int i = 0; i < ivector1.size(); i++) {        cout << ivector1[i] << " ";    }    cout << endl;     return 0; }``

1 1 1 1 1
2 1 1 1 1
1 1 1 1 1