13.C++ vector 操作

vector初始化
    vector<int> v2;
    v2.push_back(333);
    v2.push_back(444);
    v2.push_back(555);

    //初始化的两种方式
    vector<int> v3 = v2;
    while (v3.size() > 0) {
        cout << "v3尾部元素" << v3.back() << endl;
        v3.pop_back();
    }

    vector<int> v4(v2.begin(), v2.end());

    while (v4.size() > 0) {
        cout << "v4尾部元素" << v4.back() << endl;
        v4.pop_back();
    }
vector大小
    //初始化了19个元素,那么再添加就是第20个
    vector<int> v(19);
    v.push_back(200);
    v.push_back(300);
    cout << "v.size="<<v.size()<< endl;
数组方式操作vector
    cout << "数组。。。。。。。。。"<< endl;
    vector<int> v(10);
    for (int i = 0; i < 10; i++) {
        v[i] = i + 100;
    }
    for (int i = 0; i < 10; i++) {
        cout << v.at(i)<< endl;
    }
迭代器方式操作vector
    vector<int> v(10);
    for (int i = 0; i < 10; i++) {
        v[i] = i + 1000;
    }
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
        cout << *it << " ";
    }
反向迭代器操作vector
    vector<int> v(10);
    for (int i = 0; i < 10; i++) {
        v[i] = i + 1;
    }

    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << endl;
    }

    //逆向迭代器
    for (vector<int>::reverse_iterator it = v.rbegin(); it != v.rend(); it++) {
        cout << *it<< endl;
    }
vector测试
    vector<int> v1;
    cout << "length:"<<v1.size()<< endl;

    v1.push_back(1);
    v1.push_back(11);
    v1.push_back(111);

    cout << "length:" << v1.size() << endl;

    
    cout << "头部元素"<<v1.front()<< endl;

    while (v1.size() > 0) {
        cout << "尾部元素" << v1.back() << endl;
        v1.pop_back();
    }

    //修改头部元素值
    //front()返回的是一个引用,可以当左值
    v1.push_back(000);
    v1.front() = 222;

    cout << "修改后的头部元素" << v1.front() << endl;
删除元素
    vector<int> v(10);
    for (int i = 0; i < 10; i++) {
        v[i] = i + 100;
    }
    for (int i = 0; i < 10; i++) {
        cout << v.at(i) << endl;
    }
    for (vector<int>::iterator it = v.begin(); it !=v.end();) {
        if (*it == 105) {
            //删除迭代器所指向元素的时候,erase删除函数会让it自动向后移动一位
            //所以这总条件下,for循环中的it++就不需要了,另外erase之后会返回
            //下一位iterator,所以需要通过it接收一次
            it = v.erase(it);
        }
        else {
            it++;
        }
    }
    //v.erase(v.begin());
    /*v.erase(v.begin(), v.begin() + 2);*/
    for (int i = 0; i < 9; i++) {
        cout << v.at(i) << endl;
    }
插入元素
    vector<int> v(10);
    for (int i = 0; i < 10; i++) {
        v[i] = i + 100;
    }
    for (int i = 0; i < 10; i++) {
        cout << v.at(i) << endl;
    }
    v.insert(v.begin(), 99);
    v.insert(v.end(), 200);
    for (int i = 0; i < 12; i++) {
        cout << v.at(i) << endl;
    }
上一篇:12.C++ string 操作


下一篇:「免费开源」基于Vue和Quasar的crudapi前端SPA项目实战之模块管理(十四)