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

相关推荐
oy_mail31 分钟前
QoS质量配置
开发语言·智能路由器·php
oyzz12034 分钟前
PHP操作redis
开发语言·redis·php
nashane1 小时前
HarmonyOS 6学习:网络能力变化监听与智能提示——告别流量偷跑,打造贴心网络感知应用
开发语言·php·harmony app
yolo_guo1 小时前
redis++使用: hmset 与 hmget
c++·redis
凌波粒1 小时前
Java 8 “新”特性详解:Lambda、函数式接口、Stream、Optional 与方法引用
java·开发语言·idea
handler012 小时前
拒绝权限报错!三分钟掌握 Linux 权限管理
linux·c语言·c++·笔记·学习
拾贰_C2 小时前
【Google | Gemini | API | POST】怎么使用Google 的Gemini API (原生版)
开发语言·lua
t***5443 小时前
如何在Dev-C++中选择Clang编译器
开发语言·c++
橙子199110163 小时前
Java 基础相关
java·开发语言