how to use vector in C++

#include <iostream>

int main() {
    // 1. initialize
    vector<int> v0;
    vector<int> v1(5, 0);
    // 2. make a copy
    vector<int> v2(v1.begin(), v1.end());
    vector<int> v3(v2);
    // 2. cast an array to a vector
    int a[5] = {0, 1, 2, 3, 4};
    vector<int> v4(a, *(&a + 1));
    // 3. get length
    cout << "The size of v4 is: " << v4.size() << endl;
    // 4. access element
    cout << "The first element in v4 is: " << v4[0] << endl;
    // 5. iterate the vector
    cout << "[Version 1] The contents of v4 are:";
    for (int i = 0; i < v4.size(); ++i) {
        cout << " " << v4[i];
    }
    cout << endl;
    cout << "[Version 2] The contents of v4 are:";
    for (int& item : v4) {
        cout << " " << item;
    }
    cout << endl;
    cout << "[Version 3] The contents of v4 are:";
    for (auto item = v4.begin(); item != v4.end(); ++item) {
        cout << " " << *item;
    }
    cout << endl;
    // 6. modify element
    v4[0] = 5;
    // 7. sort
    sort(v4.begin(), v4.end());
    // 8. add new element at the end of the vector
    v4.push_back(-1);
    // 9. delete the last element
    v4.pop_back();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Clipboard引荐 Clipboard,即剪切板,当我们同时按动Ctrl+C时,选定的对象就被存放在了剪切板中...
    BarretX阅读 10,710评论 0 2
  • 带儿子和一众小伙伴去河北骑自行车,场地很能刺激孩子们的肾上腺素,他们嗨得很。我本不打算骑,但后来还是绕了一大圈,选...
    misang阅读 4,702评论 0 7
  • 1)重用问题:如UITableViewCells、UICollectionViewCells、UITableVie...
    世玉茹花阅读 1,176评论 0 0
  • 当年看日全食的时候对着满天繁星许了心愿,到了今天我把这个愿给忘了。岁月从来不饶人,万物皆为刍狗。
    _BlanKkk阅读 775评论 0 0