📜  C++ STL中的array :: at()

📅  最后修改于: 2021-05-30 13:03:12             🧑  作者: Mango

数组类通常比C型数组更有效,更轻量且更可靠。 C++ 11中数组类的引入为C样式数组提供了更好的替代方法。

array :: at()
此函数用于将对元素的引用返回给存在于作为函数参数给出的位置的元素。

句法:

array_name.at(position)

Parameters:
Position of the element to be fetched.

返回值:返回给定位置上元素的引用。

例子:

Input:  array_name1 = [1, 2, 3]
        array_name1.at(2);
Output: 3

Input:  array_name2 = ['a', 'b', 'c', 'd', 'e']
        array_name2.at(4);
Output: e
// CPP program to illustrate
// Implementation of at() function
#include 
using namespace std;
  
int main()
{
    // Take any two array
    array array_name1;
    array array_name2;
      
    // Inserting values
    for (int i = 0; i < 3; i++)
        array_name1[i] = i+1;
      
    for (int i = 0; i < 5; i++)
        array_name2[i] = 97+i;
          
    // Printing the element 
    cout << "Element present at position 2: " 
         << array_name1.at(2) << endl;
    cout << "Element present at position 4: " 
         << array_name2.at(4);
      
    return 0;
}

输出:

Element present at position 2: 3
Element present at position 4: e

时间复杂度:常数,即O(1)。

应用:
给定一个整数数组,从第一个位置开始以交替方式打印整数。

Input:  1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Output: 2 4 6 8 10
// CPP program to illustrate
// application of at() function
#include 
using namespace std;
  
int main()
{
    // Declare array
    array a;
      
    // Inserting values
    for (int i = 0; i < 10; i++)
        a[i] = i+1;
          
    for (int i = 0; i < a.size(); ++i) {
        if (i % 2 != 0) {
            cout << a.at(i);
            cout << " ";
        }
    }
    return 0;
}

输出:

2 4 6 8 10 
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”