【C++】STL 容器 - vector 动态数组容器 ⑤ ( vector 容器元素访问 | at 函数 | [] 运算符重载 函数 | vector 容器首尾元素访问 )






一、 vector 容器元素访问



1、vector 容器访问指定索引的元素 - at 函数


vector 容器访问指定索引的元素 , 可以使用 at() 函数 和 [] 操作符 ;


vector 类的 at 函数 , 可以访问指定索引位置的元素 , 函数原型如下 :

const_reference at(size_type pos) const;

该函数返回容器中指定位置的元素的常量引用 ;

特别注意 : 如果指定的位置超出了容器的范围 , at 函数会抛出 std::out_of_range 异常 , 在使用 at 函数之前 , 最好先检查位置是否在容器的范围内 ;

推荐使用 [0, vec.size() - 1] 闭区间之间的索引值 ;

在进行遍历时 , 推荐使用

    for (int i = 0; i < vec.size(); i++) {
    
    }

作为遍历条件 ;


代码示例 :

#include "iostream"
using namespace std;
#include "vector"

int main() {
    
    

    // 创建空的 vector 容器
    std::vector<int> vec{
    
    1, 2, 3};

    // 遍历打印 vector 容器的内容 
    for (int i = 0; i < vec.size(); i++) {
    
    
        std::cout << vec.at(i) << ' ';
    }
    std::cout << std::endl;

	
	// 控制台暂停 , 按任意键继续向后执行
	system("pause");

	return 0;
};

执行结果 :

1 2 3
Press any key to continue . . .

在这里插入图片描述


2、vector 容器访问指定索引的元素 - [] 运算符重载 函数


vector 容器可以使用 [] 运算符访问其元素 , 调用的是 [] 运算符重载 函数 , 函数原型如下 :

reference operator[](size_type pos);  

该函数返回 vector 容器中指定位置的元素的引用 ;

该 [] 运算符重载函数 与 at 函数一样 , 如果 位置参数 超出了容器的范围 , [] 运算符重载函数 会抛出异常 ;

因此,在使用 [] 运算符重载之前,也应该先检查位置是否在容器的范围内 ;


代码示例 :

#include "iostream"
using namespace std;
#include "vector"

int main() {
    
    

    // 创建空的 vector 容器
    std::vector<int> vec{
    
    1, 2, 3};

    // 遍历打印 vector 容器的内容 
    for (int i = 0; i < vec.size(); i++) {
    
    
        std::cout << vec[i] << ' ';
    }
    std::cout << std::endl;

	
	// 控制台暂停 , 按任意键继续向后执行
	system("pause");

	return 0;
};

在这里插入图片描述





二、 vector 容器首尾元素访问



1、vector 容器首尾元素访问函数


vector 容器首尾元素访问函数 :

  • 访问 vector 容器首元素 : vector 容器类的 front() 成员函数返回一个常量引用 , 表示容器中的第一个元素 ;
const_reference front() const noexcept;
  • 访问 vector 容器尾元素 : vector 容器类的 back() 成员函数返回一个常量引用 , 表示容器中的最后一个元素 ;
const_reference back() const noexcept;

2、代码示例 - vector 容器首尾元素访问


代码示例 :

#include "iostream"
using namespace std;
#include "vector"

int main() {
    
    

    // 创建空的 vector 容器
    std::vector<int> vec{
    
    1, 2, 3};

    // 遍历打印 vector 容器的内容 
    for (int i = 0; i < vec.size(); i++) {
    
    
        std::cout << vec[i] << ' ';
    }
    std::cout << std::endl;

    std::cout << "首元素 : " << vec.front() << std::endl;
    std::cout << "尾元素 : " << vec.back() << std::endl;

	
	// 控制台暂停 , 按任意键继续向后执行
	system("pause");

	return 0;
};

执行结果 :

1 2 3
首元素 : 1
尾元素 : 3
Press any key to continue . . .

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/han1202012/article/details/135082777