STL初识vector容器,stdexcept头文件

    xiaoxiao2021-03-26  33

    #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; }
    转载请注明原文地址: https://ju.6miu.com/read-659597.html

    最新回复(0)