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

相关推荐
程序员打怪兽2 分钟前
C++:类与对象,封装,继承,多态,构造/析构,重载/重写
c++
Escalating_xu17 分钟前
【C++ STL简介】从六大组件到容器、迭代器与算法协作
java·c++·算法
for_ever_love__20 分钟前
PySpark学习: 数据输出
开发语言·python·学习·spark
Brilliantwxx29 分钟前
【Linux】 进程(3)深度解析:从查看进程到进程状态
linux·服务器·网络·c++
言乐632 分钟前
Python实现自动拉人脚本示例
开发语言·windows·python·django·pygame
啊啊啊啊啊!!!!34 分钟前
【c++】二叉搜索树
开发语言·c++
归去来 兮1 小时前
Python爬虫爬取数据案例
开发语言·爬虫·python
ShineWinsu1 小时前
对于 C++:C++20中Concept(概念) 与 Coroutine(协程)的解析
linux·开发语言·网络·c++·c++20·epoll
ly76891 小时前
C 语言从入门到进阶:语法、指针、内存管理与工程实践详解
c语言·开发语言
quantdash_cc1 小时前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash