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

Array::fill() และ array::swap() ใน C++ STL


ในส่วนนี้เราจะดูการใช้งานของ array::fill() และ array::swap() ใน C++ STL

ฟังก์ชัน array::fill() ใช้เติมค่าที่กำหนดให้กับอาร์เรย์ มาดูตัวอย่าง

ตัวอย่าง

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

int main() {
    array<int, 10> arr = {00, 11, 22, 33, 44, 55, 66, 77, 88, 99};
    cout << "Array elements: ";
    for(auto it = arr.begin(); it != arr.end(); it++) {
        cout << *it << " ";
    }
    // fill array with 5
    arr.fill(5);
    cout << "\nArray elements after fill: ";
    for(auto it = arr.begin(); it != arr.end(); it++) {
        cout << *it << " ";
    }
}

ผลลัพธ์

Array elements: 0 11 22 33 44 55 66 77 88 99
Array elements after fill: 5 5 5 5 5 5 5 5 5 5

ฟังก์ชัน array::swap() ใช้สลับเนื้อหาของอาร์เรย์หนึ่งกับอีกอาร์เรย์หนึ่ง มาดูตัวอย่าง

ตัวอย่าง

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

int main() {
    array<int, 10> arr1 = {00, 11, 22, 33, 44, 55, 66, 77, 88, 99};
    array<int, 10> arr2 = {85, 41, 23, 65, 74, 02, 51, 74, 98, 22};
    cout << "Array1 elements: ";
    for(auto it = arr1.begin(); it != arr1.end(); it++) {
        cout << *it << " ";
    }
    cout << "\nArray2 elements: ";
    for(auto it = arr2.begin(); it != arr2.end(); it++) {
        cout << *it << " ";
    }
    // swap array elements
    arr1.swap(arr2);
    cout << "\nArray1 elements (After swap): ";
    for(auto it = arr1.begin(); it != arr1.end(); it++) {
        cout << *it << " ";
    }
    cout << "\nArray2 elements (After swap): ";
    for(auto it = arr2.begin(); it != arr2.end(); it++) {
        cout << *it << " ";
    }
}

ผลลัพธ์

Array1 elements: 0 11 22 33 44 55 66 77 88 99
Array2 elements: 85 41 23 65 74 2 51 74 98 22
Array1 elements (After swap): 85 41 23 65 74 2 51 74 98 22
Array2 elements (After swap): 0 11 22 33 44 55 66 77 88 99