C++ Deque::operator[] 函数



C++ 的std::deque::operator[]函数允许访问或修改特定索引处的元素,类似于数组和向量的工作方式。该函数接受单个参数(索引),并返回对该位置元素的引用。

与at()不同,它不执行边界检查,因此访问超出范围的索引会导致未定义的行为。

语法

以下是std::deque::operator[]函数的语法。

reference operator[] (size_type n);
const_reference operator[] (size_type n) const;

参数

  • n − 表示容器中元素的位置。

返回值

它返回容器中指定位置的元素。

异常

如果索引超出范围,则抛出未定义的行为。

时间复杂度

此函数的时间复杂度为常数,即 O(1)。

示例

在下面的示例中,我们将考虑operator[]函数的基本用法。

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    std::cout << "Element at given index : " << a[1] << std::endl;
    return 0;
}

输出

上述代码的输出如下:

Element at given index : B

示例

考虑以下示例,我们将修改元素。

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    a[2] = 'Z';
    for (int x = 0; x < a.size(); ++x) {
        std::cout << a[x] << " ";
    }
    std::cout << std::endl;
    return 0;
}

输出

以下是上述代码的输出:

A B Z D

示例

让我们看下面的例子,我们将访问超出范围的元素并观察输出。

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a = {01,12,23,34};
    std::cout << "Element at given index : " << a[5] << std::endl;
    return 0;
}

输出

如果我们运行上述代码,它将生成以下输出:

Element at given index : 0
deque.htm
广告
© . All rights reserved.