都是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;
}
1 当容器调用erase时,当前位置到容器末尾元素的所有的迭代器全部失效
2 当容器调用insert时,当前位置到容器末尾元素的所有的迭代器全部失效;
3 当容器调用insert时,如果引起容器内存扩容,原来容器的所有的迭代器就全部失效