Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน Array get() ใน C++ STL


ในส่วนนี้เราจะดูฟังก์ชัน get() ของ array ใน C++ STL ฟังก์ชันนี้ใช้ดึงองค์ประกอบที่ i (ith element) ของคอนเทนเนอร์ array ไวยากรณ์เหมือนด้านล่าง −

ไวยากรณ์

get<i>(array_name)

ฟังก์ชันนี้รับพารามิเตอร์บังคับ 2 ตัว ตัวแรกคือพารามิเตอร์ดัชนี (index parameter) ใช้ชี้ไปยังตำแหน่งที่ i ของอาร์เรย์ ตัวที่สองคือ array_name อาร์เรย์จริงที่จะดึงองค์ประกอบที่ i ฟังก์ชันคืนค่าองค์ประกอบที่ i

มาดูตัวอย่าง

ตัวอย่าง

#include<iostream>
#include<array>
using namespace std;

int main() {
    array<int, 10> arr = {00, 11, 22, 33, 44, 55, 66, 77, 88, 99};
    cout << "1st element: " << get<0>(arr) << endl;
    cout << "6th element: " << get<5>(arr) << endl;
    cout << "8th element: " << get<7>(arr) << endl;
    cout << "10th element: " << get<9>(arr) << endl;
}

ผลลัพธ์

1st element: 0
6th element: 55
8th element: 77
10th element: 99