关于#c++#的问题:一道关于c++vector和迭代器的问题

img


一道关于c++vector和迭代器的问题,代码最好加一点注释

都是vector容器的基本用法。push_back、insert
代码参考如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;

int comp(int a, int b)
{
    return a > b;
}


int main()
{
    int t;
    srand((unsigned int)time(0)); //生成随机数种子
    //(1)
    cout << "插入10个随机数:";
    vector<int> iv1;
    for (int i = 0; i < 10; i++)
    {
        t = rand() % 100; //生成[0,100)的随机数
        iv1.push_back(t);
        cout << t << " ";
    }
    cout << endl;
    //(2)
    t = rand() % 100; //生成[0,100)的随机数
    iv1.insert(iv1.begin(), t); //在头部插入
    cout << "在头部插入" << t << endl;
    t = rand() % 100; //生成[0,100)的随机数
    iv1.push_back(t); //在尾部插入
    cout << "在尾部插入" << t << endl;
    //(3)
    cout << "使用迭代器遍历vector:" << endl;
    vector<int>::iterator it = iv1.begin(); //迭代器
    for (; it != iv1.end(); it++)
        cout << *it << " ";
    cout << endl;
    //(4)
    sort(iv1.begin(), iv1.end(), comp); //通过comp制定排序规则
    cout << "使用sort函数从大到小排序:" << endl;
    for (it = iv1.begin(); it != iv1.end(); it++)
        cout << *it << " ";
    cout << endl;

    //(5)
    cout << "删除最后一个元素后:" << endl;
    it = iv1.end(); 
    it--;//end()是vector最后一个元素的下一个位置,所以it--后才是最后一个元素的位置
    iv1.erase(it);
    //删除最后一个元素后遍历输出
    for (it = iv1.begin(); it != iv1.end(); it++)
        cout << *it << " ";
    cout << endl;

    //(6)
    cout << "请输入要查找的元素:";
    cin >> t;
    it = find(iv1.begin(), iv1.end(), t);
    if (it != iv1.end())
        cout << "找到该元素" << endl;
    else
        cout << "该元素不存在" << endl;
    return 0;
}


您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632