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

相关推荐
朝阳58132 分钟前
rust 交叉编译指南
开发语言·后端·rust
coding者在努力1 小时前
被n整除的n位数
c++·算法
赵药师1 小时前
Win11下的VS2022 配置RGBD435i 相机
c++·vs2022·windows11·rgbd435i
量子炒饭大师1 小时前
【C++ 进阶】Cyber霓虹掩体下的代码拟态——【面向对象编程 之 多态】一文带你搞懂C++面向对象编程中的三要素之一————多态!
开发语言·c++·多态
伴我与影1 小时前
【记录】复现论文 Dftpav
c++·docker
Hical_W2 小时前
深入学习CPP17_PMR
c++·学习
xiaoshuaishuai82 小时前
C# 实现百度搜索算法逆向
开发语言·windows·c#·dubbo
yuan199972 小时前
使用模糊逻辑算法进行路径规划(MATLAB实现)
开发语言·算法·matlab
计算机安禾2 小时前
【数据结构与算法】第42篇:并查集(Disjoint Set Union)
c语言·数据结构·c++·算法·链表·排序算法·深度优先
蒸汽求职2 小时前
北美求职身份过渡:Day 1 CPT 的合规红线与安全入职指南
开发语言·人工智能·安全·pdf·github·开源协议