C++之vector

2022-12-05 15:54:50 浏览数 (1)

vector是标准库中常见的一种容器,可以用来代替数组

代码语言:javascript复制
/*
 * 版权所有  公众号  VxWorks567
 */

#include <iostream>
#include <vector>

using namespace std;

struct myStruct
    {
    int memA;
    int memB;
    };
int testVec()
{
    vector<int> vec1;          //声明类型为int的空vector
    vector<char> vec2(2);      //声明类型为char的vector, 元素数量为2
    vector<float> vec3(3,0);   //声明类型为float的vector, 元素数量为3, 初值为0
    vector<float> vec4(vec3);  //声明类型为float的vector, 初值与vec3相同
    vector<myStruct> vecStruct;//声明类型为struct的vector

    myStruct tmp;
    tmp.memA = 1;
    tmp.memB = 2;

    //push_back()在vector尾部加入元素
    vecStruct.push_back(tmp);
    tmp.memA = 2;
    vecStruct.push_back(tmp);
    tmp.memA = 3;
    vecStruct.push_back(tmp);

    //size()查询vector的元素数量
    cout << "size: " << vecStruct.size() << endl;

    //front()返回vector的第一个元素
    tmp = vecStruct.front();
    cout << "first: " << tmp.memA << " " << tmp.memB << endl;

    //back()返回vector的最后一个元素
    tmp = vecStruct.back();
    cout << "last: " << tmp.memA << " " << tmp.memB << endl;

    //erase()删除vector中某个元素
    //begin()返回指向第一个元素的iterator
    //end()返回指向尾元素的下一个位置的iterator, 即end()指示的是一个不存在的元素
    vecStruct.erase(  vecStruct.begin());
    cout << "size after erase(): " << vecStruct.size() << endl;

    //insert()在vector中插入元素
    tmp.memA = 0;
    vecStruct.insert(vecStruct.begin() 1, tmp);
    cout << "size after insert(): " << vecStruct.size() << endl;

    //pop_back()从vector尾部删除元素
    vecStruct.pop_back();
    cout << "size after pop_back(): " << vecStruct.size() << endl;

    //empty()查询vector是否为空
    vecStruct.empty();
    cout << "empty: " << vecStruct.empty() << endl;

    tmp.memA = 4;
    vecStruct.push_back(tmp);
    cout << "size after push_back(): " << vecStruct.size() << endl;
    for(UINT32 i = 0; i < vecStruct.size(); i  )
        {
        // [i]表示vector的第i个成员, 从0开始
        cout << vecStruct[i].memA << " " << vecStruct[i].memB << endl;
        }

    //erase(first, last)删除vector中多个个元素
    vecStruct.erase(vecStruct.begin(), vecStruct.begin() 2);
    cout << "size after erase(first, first 2): " << vecStruct.size() << endl;
    for(UINT32 i = 0; i < vecStruct.size(); i  )
        {
        cout << vecStruct[i].memA << " " << vecStruct[i].memB << endl;
        }

    //clear()清空vector
    vecStruct.clear();
    cout << "size after clear(): " << vecStruct.size() << endl;
    return 0;
    }

0 人点赞