CPP Range-based for loop

for döngüsüne benzer bir yapı. Daha pratik bir kullanıma sahip. Sıralı bir container üzerinde baştan sona tek tek elemanları getirir. Genel yapısı şu şekildedir

burada vec içindeki değerler baştan sona tek tek kopyası oluşturulup i ye atanıyor

for (auto i : vec)
    cout << i << '-';

kopyasını oluşturmak istemiyorsak & kullanmamız lazım

for (auto& i : vec)
    cout << i << '-';

Örnek:

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

void vprint(vector<float> vec) {
    for (float i : vec)
        cout << i << '-';
    cout << endl;
}

int main() {
    // Basic 10-element integer array.
    int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Range-based for loop to iterate through the array.
    for (int y : x) { // Access by value using a copy declared as a specific type.
                       // Not preferred.
        cout << y << " ";
    }
    cout << endl;

    vector<float> sayilar{10,82,54,25};
    vprint(sayilar);

}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *