C++ 99 之 容器存取

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;
#include <vector>

void printVector(vector<int>& v){
    for(vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
}
int main()
{
    vector<int>v1;
    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(3);
    v1.push_back(4);

    // 

    try{
        cout << v1.at(2) << endl;

        // cout << v1[2] << endl;

    }
    catch(out_of_range& e){
        cout << e.what()<< endl;
    }

    // front();  // 返回容器中第一个数据元素
    // back();   // 返回容器中最后一个数据元素
    cout << v1.front()<< endl;
    cout << v1.back() << endl;
    
    return 0;
}

vector数据存取操作

|--------------------------------------------------------------------------------------------------------------------------------------------|
| at(int idx); //返回索引idx所指的数据,如果idx越界,抛出out_of_range异常。 operator[];//返回索引idx所指的数据,越界时,运行直接报错 front();//返回容器中第一个数据元素 back();//返回容器中最后一个数据元素 |

相关推荐
悲伤小伞10 分钟前
Linux_Socket_UDP
linux·服务器·网络·c++·网络协议·udp
丛雨要玩游戏20 分钟前
字符函数和字符串函数
c语言·开发语言·算法
八个程序员35 分钟前
自定义函数(C++)
开发语言·c++·算法
ad钙奶长高高41 分钟前
【C语言】初始C语言
c语言·开发语言·算法
梓仁沐白42 分钟前
csapp实验一:datalab
开发语言
侯小啾1 小时前
【17】C语言-gets() 与 fgets() 函数
c语言·开发语言
胡桃夹夹子1 小时前
存档111111111
java·开发语言
不会编程的小寒1 小时前
C++ 中string的用法
java·开发语言
想搞艺术的程序员1 小时前
Go Error 全方位解析:原理、实践、扩展与封装
开发语言·后端·golang