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

相关推荐
大圣编程1 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
upgrador1 小时前
基础知识:C++ STL构造函数的左闭右开惯例及其实现原理
开发语言·c++
yoothey2 小时前
报废审批流规则引擎设计——责任链模式完整实现
linux·开发语言·bash
geovindu3 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
wuyk5553 小时前
24. C 语言模块化:不是拆几个.c 文件那么简单
c语言·开发语言·stm32·单片机
凯瑟琳.奥古斯特3 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
林中青木4 小时前
CT重构原理及C++代码实现
c++·计算机视觉·重构
AC赳赳老秦4 小时前
防火墙规则批量配置实战:OpenClaw 自动生成模板、批量下发与合规性校验全解析
java·开发语言·人工智能·python·github·php·openclaw
满天星83035774 小时前
Protobuf的介绍及使用
c++
☆cwlulu4 小时前
调试排查工具介绍(gdb、strace、Valgrind等)
开发语言·c++·嵌入式硬件·ubuntu