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

相关推荐
2301_7634724610 小时前
C++中的享元模式高级应用
开发语言·c++·算法
不会代码的小测试10 小时前
UI自动化-针对验证码登录的系统,通过首次手动登录存储cookie的方式后续访问免登录方法
开发语言·python·selenium
weixin_4589232010 小时前
分布式日志系统实现
开发语言·c++·算法
爱装代码的小瓶子10 小时前
【C++与Linux】文件篇(2)- 文件操作的系统接口详解
linux·c++
开发者小天10 小时前
python中calss的用法
开发语言·python
拾光Ծ10 小时前
【优选算法】双指针算法:专题二
c++·算法·双指针·双指针算法·c++算法·笔试面试
沉默-_-10 小时前
MyBatis 学习笔记
java·开发语言·tomcat
会游泳的石头10 小时前
构建企业级知识库智能问答系统:基于 Java 与 Spring Boot 的轻量实现
java·开发语言·spring boot·ai
m0_7482299910 小时前
Laravel4.x核心更新全解析
开发语言·php
j_xxx404_10 小时前
C++算法入门:滑动窗口合集(长度最小的子数组|无重复字符的最长字串|)
开发语言·c++·算法