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();//返回容器中最后一个数据元素 |

相关推荐
黄贵根5 小时前
JavaScript实现教培行业意向登记系统
开发语言·javascript·ecmascript
2401_868534788 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
zzzll11118 小时前
Claude Code离线安装方案揭秘
开发语言·php
wling03019 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
郝学胜-神的一滴9 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj10 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_11 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
雨田言炎13 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
程序喵大人13 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
SomeB1oody14 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程