STL初识vector容器,stdexcept头文件

#include <cmath>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector> 
#include <stdexcept>	//因为要使用out_of_range 这是一个类class 
						//C++异常类
						//属于运行时错误,如果使用了一个超出有效范围的值,就会抛出此异常。
						//也就是一般常说的越界访问。
#include <iterator>		
						//因为要使用ostream_iterator 
using namespace std;

int main()
{
	const int SIZE=5;	//const int类型是只读read-only,一旦初始化过后不能改变 
	cout<<SIZE<<endl;
	cout<<SIZE+5<<endl;
						//SIZE=SIZE+100; 这样显然会报错(assignment of read-only variable 'SIZE')
	cout<<"*********************"<<endl;
	int a[SIZE]={1,2,3,4,5};
	vector<int> v(a,a+5);	//构造函数 
	try
	{
		v.at(100)=7;
	}		
	catch(out_of_range e)
	{
		cout<<e.what()<<endl;
	}
	//v.erase(5);	//这样会报错(no matching function for call to 'std::vector<int>::erase(int)') 
	cout<<v.front()<<","<<v.back()<<endl;
	v.erase(v.begin());	//v.begin()是指向第一个元素的迭代器(指针) 
	ostream_iterator<int> output(cout,"*");	//定义了一个ostream_iterator对象(ostream_iterator<int>是类型,可以通过cout输出以*分割的一个个数字 
	copy(v.begin(),v.end(),output);	//导致v的内容在cout上输出 
	v.erase(v.begin(),v.end());		//等效于v.clear()
	if(v.empty())
		cout<<"empty"<<endl;
	v.insert(v.begin(),a,a+SIZE);	 //在v.begin()前插入a,a+SIZE这段地址指向的值,
									//为什么是在前(可以类比analogy:v2.insert(v2.begin()+2,13);) 
	copy(v.begin(),v.end(),output); 
	
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值