C++ STL容器vector篇(三) vector容器大小和数组大小, 插入和删除元素, 存储和读取元素

312 阅读1分钟

vector容器的大小(capacity)和存放数据的大小(size)

#include <iostream>
#include <vector>

using namespace std;

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

void test1()
{
    // 初始化向量并赋初值(尾插)
    vector<int> v1;
    for (int i = 0; i < 5; i++)
    {
        v1.push_back(i * 2 + 1);
    }
    // 遍历
    printV(v1);

    if (v1.empty())
    {
        cout << "empty" << endl;
    }
    else
    {
        cout << "not empty" << endl;
        cout << "capacity: " << v1.capacity() << endl;
        cout << "size: " << v1.size() << endl;
    }

    // resize()函数重新指定容器的大小
    // 可以使用重载的版本指定变大size后需要向数组中填充的值
    v1.resize(10, 333);
    printV(v1);
    cout << "capacity: " << v1.capacity() << endl;
    cout << "size: " << v1.size() << endl;

    v1.resize(5);
    cout << "capacity: " << v1.capacity() << endl;
    cout << "size: " << v1.size() << endl;
}

int main(int argc, char const *argv[])
{
    test1();
    return 0;
}

vector容器插入和删除元素

#include <iostream>
#include <vector>

using namespace std;

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

void test1()
{
    // 尾插法插入元素
    vector<int> v;
    for (int i = 0; i < 5; i++)
    {
        v.push_back(i * 2 + 1);
    }
    // 遍历vector
    printV(v);
    // 1 3 5 7 9 

    // 尾部删除元素(尾删)
    v.pop_back();
    printV(v);
    // 1 3 5 7 

    // 指定元素插入, 第一个参数需要传入迭代器(指向pos位置)
    v.insert(v.begin(), 10);
    printV(v);
    // 10 1 3 5 7 

    // 指定元素插入, 传入迭代器, 插入count个elem元素
    v.insert(v.begin() + 1, 3, 9);
    printV(v);
    // 10 9 9 9 1 3 5 7 

    // 删除迭代器指向的元素
    v.erase(v.end() - 1);
    printV(v);
    // 10 9 9 9 1 3 5 

    // 删除区间(左闭右开区间)的元素
    v.erase(v.begin(), v.end() - 2);
    printV(v);
    // 3 5 
}

int main(int argc, char const *argv[])
{
    test1();
    return 0;
}

vector容器存储和读取元素

#include <iostream>
#include <vector>

using namespace std;

/*
C++ vector 数据存储和读取
*/

void test1()
{
    // 尾插法插入元素
    vector<int> v;
    for (int i = 0; i < 5; i++)
    {
        v.push_back(i * 2 + 1);
    }

    // 1. 利用重载的[] 遍历打印vector中每一元素
    for (int i = 0; i < v.size(); ++i)
    {
        cout<<v[i]<<" ";
    }
    cout<<endl;
    // 1 3 5 7 9 

    // 2. 利用at()函数进行遍历(访问元素)
    for (int i = 0; i < v.size(); ++i)
    {
        cout<<v.at(i)<<" ";
    }
    cout<<endl;
    // 1 3 5 7 9 

    // 3. 读取容器第一个元素和最后一个元素
    cout<<"front: "<<v.front()<<"  back: "<<v.back()<<endl;
    // front: 1  back: 9

}

int main(int argc, char const *argv[])
{
    test1();
    return 0;
}