Vector容器
模板向量的一些其他成员函数:重载操作符[] 返回容器中某一个元素函数frond()和back()返回第一个和最后一个元素函数insert()在一个给定的位置插入到一个新的元素功能push_back()和pop_back()添加或删除最后一个成员函数具体的可以参考函数库,看看有哪些具体的可以使用的。#include <iostream>#include <.
·
模板向量的一些其他成员函数:
- 重载操作符[] 返回容器中某一个元素
- 函数frond()和back()返回第一个和最后一个元素
- 函数insert()在一个给定的位置插入到一个新的元素
- 功能push_back()和pop_back()添加或删除最后一个成员函数
具体的可以参考函数库,看看有哪些具体的可以使用的。
#include <iostream>
#include <vector> //容器
#include <algorithm>//算法
#include<iterator>//迭代器
using namespace std;
void main()
{
const int SIZE = 6;
int array[SIZE] = { 1, 2, 3, 4, 5, 6 };
//声明一个int类型集合的容器,并使用数组a对容器进行初始化
vector<int> v(array, array + SIZE);
cout << "第一个元素:" << v.front() << "\n 最后一个元素:" << v.back() << endl;
//通过下标操作符和at函数来修改容器中的元素
//at更安全,会检查下表是否越界
v[1] = 7;
v.at(2) = 10;
//要插入的位置,要插入的值
//第二个元素插入,变为七个元素
v.insert(v.begin() + 1, 22);
//尾部插入19 变为8个元素
v.push_back(19);
//声明迭代器;用来遍历
vector<int>::iterator iter;
iter = v.begin();//迭代器指向第一个元素
while (iter != v.end())
{
cout << *iter << endl;//类似指针
iter++;
}
//使用算法空间中的方法
//找到了,返回其迭代器
iter = find(v.begin(), v.end(), 22);
if (iter!=v.end())
{
cout << "loacation:" << (iter - v.begin()) << endl;
}
else
{
cout << "not find" << endl;
}
//系统最大容量,计算机能够开辟的最大空间
cout << "The Max size of the vector is:" << v.max_size();
//当前最大容量,
cout << "目前的容量是:" << v.capacity() << endl;
}
更多推荐
所有评论(0)